Swift 如何生成一个自定义UIVIEW,该UIVIEW是一个UIVIEVIEW,它有一个圆孔,在中间可以穿透到UIIVIEVIEW?

Swift 如何生成一个自定义UIVIEW,该UIVIEW是一个UIVIEVIEW,它有一个圆孔,在中间可以穿透到UIIVIEVIEW?,swift,cashapelayer,Swift,Cashapelayer,我正试图在UIImageView上方的UIView中打一个圆孔,通过这个圆孔可以看到下面的图像(稍后我想通过手势识别器与此图像进行交互)。我有两个问题,我无法使圆孔居中于UIImageView的中间(它当前居中于屏幕的左上角),并且我得到的效果与我试图达到的效果相反(圆之外的一切都是可见的)。下面是我的代码。有人能给我建议吗 结果: 控制台: setup.imgView.center: (0.0, 0.0) imgView.center: (207.0, 359.0) 试着去掉你的覆盖,改为

我正试图在UIImageView上方的UIView中打一个圆孔,通过这个圆孔可以看到下面的图像(稍后我想通过手势识别器与此图像进行交互)。我有两个问题,我无法使圆孔居中于UIImageView的中间(它当前居中于屏幕的左上角),并且我得到的效果与我试图达到的效果相反(圆之外的一切都是可见的)。下面是我的代码。有人能给我建议吗

结果:

控制台:

setup.imgView.center: (0.0, 0.0)
imgView.center: (207.0, 359.0)

试着去掉你的覆盖,改为添加下面的UIView。它基本上是一个带有巨大黑色边框的圆形UIView,但它占据了整个屏幕,用户无法分辨。仅供参考,您需要使用.frame在屏幕上定位项目。下图将圆圈置于屏幕中央。如果需要图像的中心,请将self.view.frame替换为self。imgView.frame。。。使用circleSize和borderSize进行游戏,直到获得所需的圆大小

    let circle = UIView()
    let circleSize: CGFloat = self.view.frame.height * 2 //must be bigger than the screen
    let x = (self.view.frame.width / 2) - (circleSize / 2)
    let y = (self.view.frame.height / 2) - (circleSize / 2)
    circle.frame = CGRect(x: x, y: y, width: circleSize, height: circleSize)

    let borderSize = (circleSize / 2) * 0.9 //the size of the inner circle will be circleSize - borderSize
    circle.backgroundColor = .clear
    circle.layer.cornerRadius = circle.frame.height / 2
    circle.layer.borderColor = UIColor.black.cgColor
    circle.layer.borderWidth = borderSize

    view.addSubview(circle)

你想想象成一个圆,或者你想要一个空白的圆圈在中间,在背景中有一个图像?@ PubRead我希望屏幕是暗的但是透明的,中间的圆孔可以看到下面的图像,我想以后通过圆孔与图像交互(通过Pangestress)。不是黑色背景,我希望它在圆圈周围是透明的(alpha 0.5)?只需将UIColor.black.cgColor更改为UIColor.black.withAlphaComponent(0.5.cgColor)或任何你想要的alpha。你知道如何使用view.layer.mask来实现这一点吗?我可能会在不完全需要自定义对象时尽量避免绘制它们。不过我对它不是很熟悉,所以也许其他人可以帮忙。
    let circle = UIView()
    let circleSize: CGFloat = self.view.frame.height * 2 //must be bigger than the screen
    let x = (self.view.frame.width / 2) - (circleSize / 2)
    let y = (self.view.frame.height / 2) - (circleSize / 2)
    circle.frame = CGRect(x: x, y: y, width: circleSize, height: circleSize)

    let borderSize = (circleSize / 2) * 0.9 //the size of the inner circle will be circleSize - borderSize
    circle.backgroundColor = .clear
    circle.layer.cornerRadius = circle.frame.height / 2
    circle.layer.borderColor = UIColor.black.cgColor
    circle.layer.borderWidth = borderSize

    view.addSubview(circle)