【问题标题】:Drawing a circle cutout in UIView (Swift)在 UIView (Swift) 中绘制圆形切口
【发布时间】:2016-02-21 06:45:16
【问题描述】:

我正在尝试制作一个黑色的 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 转发触摸事件。

【问题讨论】:

    标签: ios swift uiview


    【解决方案1】:

    不要覆盖drawRect,而是使用CAShapeLayer作为掩码:

    let blackView = UIView()
    blackView.frame = view.frame
    let mask = CAShapeLayer()
    mask.path = UIBezierPath(ovalInRect: CGRectInset(view.frame, 30, 30)).CGPath
    blackView.layer.mask = mask
    

    【讨论】:

    • 是否还需要将 blackView 的 backgroundColor 设置为黑色?
    • 是的,设置为黑色。
    • 追加.CGPath到UIBezierPath(ovalInRect: CGRectInset(view.frame, 30, 30)) blackView.layer.mask = mask
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多