I have trouble clipping the image in SwiftUI
Here is the code with minimal wrong-working example:
struct TestView: View {
var body: some View {
Image("iPhone13Pro")
.resizable()
.scaledToFill()
.frame(width: 400, height: 400)
.border(.black)
.clipped()
.onTapGesture {
print("click")
}
}
}
As I expect, a tap outside the frame should print nothing to the console, but it prints
As a result, the image is not getting clipped, and I am seeing the click
in the console
The result seems to be rendered right, but the touch outside the image (red arrows) still produces the console log
The image is not square, that is more horizontal, so, without .clipped()
that looks like this:
I figured out the answer
.clipped()
is responsible only for the visual representation of the view
To actually restrict the view by the frame and prevent it to cross the border, use .contentShape(_:)
That solves the problem for me