用圆形路径剪辑 UIView Swift iOS

Clip a UIView with a circle path Swift iOS

我正在尝试将我的相机预览 (UIView) 剪裁到圆形路径内,但蒙版似乎没有剪裁我的视图。

        let preview = cameraController!.previewLayer
        preview.translatesAutoresizingMaskIntoConstraints = false
        _view.translatesAutoresizingMaskIntoConstraints = false
        


        let path = UIBezierPath(arcCenter: CGPoint(x: _view.frame.size.width/2, y: _view.frame.size.height/2),
                                radius: _view.frame.size.width/2.5,
                                startAngle: CGFloat(0).toRadians(),
                                endAngle: CGFloat(360).toRadians(),
                                clockwise: false)
        
        path.reversing()
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 5
        preview.layer.mask = shapeLayer
        preview.layer.addSublayer(shapeLayer)
        preview.clipsToBounds = true
        
        _view.addSubview(preview)

我在这里缺少什么?

大部分设置都很好,只是改变了一些东西让它工作:

func maskPreview()
{
    // No change from your code
    let path = UIBezierPath(arcCenter: CGPoint(x: view.frame.size.width/2,
                                               y: view.frame.size.height/2),
                            radius: view.frame.size.width/2.5,
                            startAngle: CGFloat(0).toRadians(),
                            endAngle: CGFloat(360).toRadians(),
                            clockwise: false)
    
    // Removed this, not sure it was needed
    // Add it back if needed
    //path.reversing()
    
    // No change
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    
    // This should not be transparent since we need
    // the camera preview to be seen through here
    shapeLayer.fillColor = UIColor.white.cgColor
    
    // No change
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 5
    
    // No change
    previewView.layer.mask = shapeLayer
    
    // You do not need to add the shape layer as a sublayer
    // after defining it as your mask
    // previewView.layer.addSublayer(shapeLayer)
    
    // No change
    previewView.clipsToBounds = true
}

最终结果

更新以讨论遮罩层颜色

maskdocumentation 定义了 Alpha 通道决定允许显示哪些内容(如果有)的行为。

mask

An optional view whose alpha channel is used to mask a view’s content.

Discussion

The view’s alpha channel determines how much of the view’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.

填充颜色不是您正确指出的圆圈颜色。你可以改变它,只要它不是清晰的颜色就没关系。它决定遮罩是否渲染底层视图。

要实际添加一些颜色,我相信你不能直接通过遮罩层来完成,你需要一个中间层。