user16109489
user16109489

Reputation:

SwiftUI - How to partially mask/clip an image?

I want to my image object to be become partially masked when moving (via animation) across a border. For reference, I want to make something like this:

Position 1 Position 2 Position 3
Red circle fully visible Red circle half cut off by right border Red circle almost completely cut off by right border

Hiding the image behind another image (and create a clipped illusion) will not work because my background may be dynamic. Any advice is greatly appreciated. Thanks!

Upvotes: 1

Views: 1519

Answers (1)

aheze
aheze

Reputation: 30278

create a clipped illusion) will not work

Check out the .clipped() modifier. It's the real thing, not an illusion.

struct ContentView: View {
    @State var offset = CGFloat(0)
    
    var body: some View {    
        Group {
            Image(systemName: "circle.fill")
                .foregroundColor(.red)
                .offset(x: offset, y: 0)
        }
        .frame(width: 80, height: 80)
        .border(Color.green) /// just for clarity, you can remove this
        .clipped() /// use this to prevent circle from going past borders
        .onAppear {
            withAnimation(.linear(duration: 5)) {
                offset = 100
            }
        }
    }
}

Result:

Circle moving right and past the border, but as soon as it gets to the border it starts clipping

Upvotes: 2

Related Questions