带有圆角 UIKit 的 UIImageView 的可点击区域

Tappable zone for UIImageView with rounded corners UIKit

我有一个有趣的问题 - 有一个带圆角的正方形 UIImageView(这使它成为一个圆),我这样做是为了每当你触摸视图时都会发生一些事情,但问题是圆外的区域在视图框架内仍然可以点击,我不知道如何修复它。

明确地说,我希望我的视图只能在圆圈内点击。有办法吗?

这是我的代码片段:

    @IBOutlet weak var profilePictureView: UIImageView? //it is 240x240

    override func viewDidLoad() {
        super.viewDidLoad()
        profilePictureView?.layer.cornerRadius = 240 / 2
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleProfilePictureTap(_:)))
        profilePictureView?.addGestureRecognizer(tap)
        profilePictureView?.isUserInteractionEnabled = true
    }

将视图控制器指定为识别器的委托,并过滤识别器接收到的触摸:

func viewDidLoad() {
    ...
    tap.delegate = self
}

func gestureRecognizer(_ gr: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    let bezierPath = UIBezierPath(roundedRect: profilePictureView.bounds, cornerRadius: profilePictureView.layer.cornerRadius)
    let point = touch.location(in: profilePictureView)
    return bezierPath.contains(point)
}