Swift CAShapeLayer,一个火柴人,一个遮罩

火柴人

贴代码:

        let path = UIBezierPath()
        path.move(to: CGPoint.init(x: 175, y: 100))
        
        path.addArc(withCenter: CGPoint.init(x: 150, y: 100), radius: 25, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
        path.move(to: CGPoint.init(x: 150, y: 125))
        path.addLine(to: CGPoint.init(x: 150, y: 175))
        path.addLine(to: CGPoint.init(x: 125, y: 225))
        path.move(to: CGPoint.init(x: 150, y: 175))
        path.addLine(to: CGPoint.init(x: 175, y: 225))
        path.move(to: CGPoint.init(x: 100, y: 150))
        path.addLine(to: CGPoint.init(x: 200, y: 150))
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 5
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineCap = kCALineCapRound
        shapeLayer.path = path.cgPath
        self.view.layer.addSublayer(shapeLayer)

效果图:

Swift CAShapeLayer,一个火柴人,一个遮罩_第1张图片
火柴人.png

遮罩

贴代码:

let view = UIView.init(frame: CGRect.init(x: 50, y: 50, width: 100, height: 100))
        view.backgroundColor = UIColor.cyan
        self.view.addSubview(view)
        
        let path = UIBezierPath()
        path.move(to: CGPoint.init(x: 0, y: 0))
        path.addLine(to: CGPoint.init(x: 70, y: 0))
        path.addLine(to: CGPoint.init(x: 100, y: 30))
        path.addLine(to: CGPoint.init(x: 70, y: 60))
        path.addLine(to: CGPoint.init(x: 70, y: 100))
        path.addLine(to: CGPoint.init(x: 0, y: 100))
        path.close()
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        view.layer.mask = shapeLayer

效果图:

Swift CAShapeLayer,一个火柴人,一个遮罩_第2张图片
遮罩.png

你可能感兴趣的:(Swift CAShapeLayer,一个火柴人,一个遮罩)