SwiftUI

trim

Phililip 2022. 6. 6. 02:14
728x90

안녕하세요.

 

이번에는 trim 수식어에 대해 알아볼게요.

 


trim 수식어는 아래처럼 생겼어요.

 

 

 

 

trim 수식어를 사용하면 Shape 뷰의 path를 일정 부분 잘라서 반환해줍니다.

 

정확하게는 Shape의 전체 경로를 1이라고 봤을 때, 1 x startFraction 지점부터 1 x endFraction 지점까지의 Shape을 반환해주는 것이에요.

(당연히 startFraction과 endFraction은 0 ~ 1 사이의 값을 가집니다)

 

만약 시작 지점이 끝나는 지점보다 뒤에 있을 경우(즉, startFraction >= endFraction인 경우)에는 아무것도 출력되지 않습니다.

 

 

예를 들어서, 아래 같은 Shape이 있다고 했을 때

Path { path in
    path.addLines([
        .init(x: 2, y: 1),
        .init(x: 1, y: 0),
        .init(x: 0, y: 1),
        .init(x: 1, y: 2),
        .init(x: 3, y: 0),
        .init(x: 4, y: 1),
        .init(x: 3, y: 2),
        .init(x: 2, y: 1)
    ])
}
.scale(50, anchor: .topLeading)
.stroke(Color.black, lineWidth: 3)

 

trim 수식어를 넣으면, 

Path { path in
    path.addLines([
        .init(x: 2, y: 1),
        .init(x: 1, y: 0),
        .init(x: 0, y: 1),
        .init(x: 1, y: 2),
        .init(x: 3, y: 0),
        .init(x: 4, y: 1),
        .init(x: 3, y: 2),
        .init(x: 2, y: 1)
    ])
}
.trim(from: 0.25, to: 1.0)  ✅
.scale(50, anchor: .topLeading)
.stroke(Color.black, lineWidth: 3)
.frame(width: 200, height: 200)

 

1/4 지점 이후부터 끝까지 출력되는 이런 모양이 될 것이에요.

 

이해가 좀 되시나요??

 

startFraction = 0.0, endFraction = 1.0을 넣으면 Shape 전체가 출력되겠죠??ㅎㅎ

 

 

 

 

trim을 이용하면 아래처럼 Timer도 쉽게 구현이 가능하니 알아두면 좋을 것 같아요ㅎㅎ

struct ContentView: View {
    @State private var seconds: Int = 0
    var body: some View {
        Circle()
            .trim(from: 0, to: Double(seconds) / 60.0)
            .stroke(.red, lineWidth: 5)
            .frame(width: 200, height: 200)
            .onAppear {
                Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
                    withAnimation {
                        if seconds >= 60 {
                            seconds = 0
                        } else {
                            seconds = seconds + 10
                        }
                    }
                }
            }
            .rotationEffect(Angle(degrees: -90))
    }
}

 

 

 

 

 

 


이번 글은 여기서 마무리.

 

 

 

반응형