I have the following view displaying a book image:
struct MaskContentView: View {
var body: some View {
ZStack {
Rectangle()
.fill(LinearGradient(colors: [.red, .green], startPoint: .top, endPoint: .bottom))
Rectangle()
.fill(LinearGradient(colors: [.red, .purple, .green], startPoint: .top, endPoint: .bottom))
.padding(10)
Rectangle()
.fill(LinearGradient(colors: [.yellow, .green], startPoint: .top, endPoint: .bottom))
.padding(20)
.overlay(alignment: .center) {
Image("book")
.resizable()
.aspectRatio(contentMode: .fill)
.colorMultiply(.black)
.opacity(0.1)
.rotationEffect(.degrees(-20), anchor: .center)
.offset(x: 50.0, y: 10)
.clipShape(Rectangle())
.clipped()
}
Text("Tourism")
.foregroundStyle(.white)
.font(.largeTitle)
}
.frame(width: 200, height: 250)
}
}
I’m trying to clip the image to the rectangle to which it’s added as an overlay but it’s overflowing onto the background rectangles. How can I achieve this?
The image:
Current Result:
Clipping the rectangle containing the overlay doesn’t fix it either:
2
Answers
You should clip the
Rectangle
instead, to remove the part of the image that’s "sticking out" of the rectangle’s frame.If you want to clip the image with the green-yellow area only, you should add the
padding
of the rectangle last, after clipping.Alternatively, don’t use an
overlay
and just add the image to theZStack
, and use an insetted rectangle as the clip shape.}
You can see the result in the attached image.