Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask/clip the bottom part of an Image in SwiftUI?

Tags:

swiftui

Currently masking an image in SwiftUI seems really easy and can either be achieved using something like:

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

or even .mask(). Is there a way of controlling which part of the image is masked by specifying .center, .bottom, .etc? So far I've been playing around with the offset but I was wondering if there might be a simpler way.

like image 281
cyril Avatar asked Oct 21 '25 12:10

cyril


1 Answers

.clipShape() needs a shape, so if you are going to be clipping the bottom often, you may create an ad hoc shape. Something like this:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("mypic")
            .aspectRatio(contentMode: .fit)
            .clipShape(BottomClipper(bottom: 100))
    }
}

struct BottomClipper: Shape {
    let bottom: CGFloat

    func path(in rect: CGRect) -> Path {
        Rectangle().path(in: CGRect(x: 0, y: rect.size.height - bottom, width: rect.size.width, height: bottom))
    }
}
like image 72
kontiki Avatar answered Oct 24 '25 03:10

kontiki