Reputation: 3005
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.
Upvotes: 4
Views: 10248
Reputation: 17570
You can combine padding with the shape. This might be the simpler way you were looking for?
Image("profile")
// Add padding to sides of the shape to control what is masked
.mask(Rectangle().padding(.bottom, 20))
.border(Color.orange)
(Excerpt from the book "SwiftUI Views")
Upvotes: 4
Reputation: 40509
.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))
}
}
Upvotes: 6