Nokt
Nokt

Reputation: 51

SwiftUI: clipping an image to shape

I'm currently working on some loading screen in SwiftUI and want to implement some kind of image animation with a simple path. I've done a simple Shape-animation with the path, but Ive stuck with clipping an image to it. Is it possible?

I just want my image to simply fly over the screen (with a configurable path). Imagine that the stroke has a color of background, so we won't see it. Thanks!

struct loadingPath: Shape {
    func path(in rect: CGRect) -> Path {
        let path =
        Path { path in
            path.move(to: CGPoint(x: rect.midX, y: rect.midY))
            path.addQuadCurve(to: CGPoint(x: 230, y: 200), control: CGPoint(x: -100, y: 300))
            path.addQuadCurve(to: CGPoint(x: 90, y: 400), control: CGPoint(x: 400, y: 130))
            path.addLine(to: CGPoint(x: 90, y: 600))
        }
        return path
    }
}

.........

var body: some View {
            ZStack {
                loadingPath()
                    .trim(from: 0, to: x)
                    .stroke(Color.purple)
                    .frame(width: 200, height: 200)
                    .onAppear() {
                        withAnimation(Animation.easeInOut(duration: 3).delay(0.5)) {
                            self.x = 1
                        }
                    }
}

Upvotes: 2

Views: 1375

Answers (1)

Amisha Italiya
Amisha Italiya

Reputation: 246

If you want to give shape and then want to clipped it then use following :

.clipShape(RoundedRectangle(cornerRadius: 55,
        style: .continuous))

Or if you you want to clipped image according to it's frame then you can simply clipped it after give it frame like following :

.
.
loadingPath()
   .trim(from: 0, to: x)
   .stroke(Color.purple)
   .frame(width: 200, height: 200)
   .clipped()
   .onAppear() { ... }

Upvotes: 2

Related Questions