在UIView(斯威夫特)画一个圆形镂空

时间:2016-02-21 06:45:17

标签: ios swift uiview

我正在尝试制作一个黑色的UIView,中间有一个透明的圆圈。到目前为止我的代码:

class MyView: UIView {

    override var frame: CGRect {
        didSet {
            setNeedsDisplay()
        }
    }

  override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        for subview in subviews as [UIView] {
            if !subview.hidden && subview.alpha > 0 && subview.userInteractionEnabled && subview.pointInside(convertPoint(point, toView: subview), withEvent: event) {
                return true
            }
        }
        return false
    }



    override func drawRect(rect: CGRect) {

        let contextRef = UIGraphicsGetCurrentContext()
        let circleRect = CGRect(x: 67, y: 214, width: 240, height: 240)
        CGContextAddEllipseInRect(contextRef, circleRect)
        CGContextClip(contextRef)

        CGContextSetRGBFillColor(contextRef, 0.0, 0.0, 0.0, 0.6)
        CGContextFillRect(contextRef, rect)



    }

}

在我的UIViewController中,我像这样初始化视图:

let blackView = MyView()
blackView.frame = view.frame
view.addSubview(blackView)

我只有一个没有切口的全黑屏幕。我在这做错了什么?一个指针将不胜感激!感谢。

编辑:如果可能的话,我需要在drawRect中执行此操作,而不是添加图层,因为我使用pointsInside转发触摸事件。

1 个答案:

答案 0 :(得分:0)

不要覆盖for (int i = 1; i <= numRows; i++){ for (int j = 1; j <= numCols; j++){ System.out.print(i + char.forDigit(65 + j) + " "); } } ,而是使用drawRect作为掩码:

CAShapeLayer