kcstricks
kcstricks

Reputation: 1579

SwiftUI: How to clip just the bottom of an image

I have an image which I wish to pin to the top of the view with a height of 200. I started with the following:

struct ContentView: View {
    var body: some View {
        VStack {
            Image("frog")
                .resizable()
                .scaledToFill()
                .frame(height:200)

            Spacer()
        }
    }
}

which gives me:

enter image description here

You can see the frame (with height 200) outlined in blue. Now, I want the image to continue to spill out of the safe zone to fill the top of the view, as it is doing. But I want clip the image at its bottom frame, so I get something like this:

enter image description here

I'd also be fine with something like this, where the whole image is shifted upwards to where the natural bottom of the image is at the bottom of the frame:

enter image description here

I've tried a wide array of modifiers, as well as using GeometryReader but have not been able to achieve either result. I need this to work for images of arbitrary dimensions.

Upvotes: 9

Views: 4225

Answers (2)

Asperi
Asperi

Reputation: 258601

Here is alternate that gives you effect of your 2nd screenshot:

Image("frog")
    .resizable()
    .scaledToFill()
    .frame(height:200)
    .mask(Rectangle().edgesIgnoringSafeArea(.top)) // << here !!

Upvotes: 13

sfung3
sfung3

Reputation: 2387

To shift the image upwards you can do the following:

.frame(height:200, alignment: .bottom)

Upvotes: 10

Related Questions