Swift小记:利用mask遮罩,剪出一个定位头像

2019-07-06  本文已影响0人  齐舞647

数学知识:

效果如图:

代码如下:

class ViewController: UIViewController {
    
    var headView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let circleCenter: CGPoint = CGPoint(x: 75.0, y: 75.0)
        let circleRadius: CGFloat = 50.0
        let startAngle: Double = -75.0  // 开始角度
        let endAngle: Double = 255.0    // 结束角度
        let arrowDistance: CGFloat = 10.0 // 箭头衍生距离
        
        let PI = Double.pi
        let path:UIBezierPath = UIBezierPath.init()
        path.addArc(withCenter: circleCenter, radius: circleRadius, startAngle:  CGFloat(startAngle/180 * PI) , endAngle: CGFloat(endAngle/180 * PI), clockwise: true)
        path.move(to: CGPoint(x: circleCenter.x, y: circleCenter.y - circleRadius - arrowDistance))
        path.addLine(to: CGPoint(x: circleCenter.x + CGFloat(Double(circleRadius) * cos(startAngle/180 * PI)), y: circleCenter.y + CGFloat(Double(circleRadius) * sin(startAngle/180 * PI))))
        path.addLine(to: CGPoint(x: circleCenter.x + CGFloat(Double(circleRadius) * cos(endAngle/180 * PI)), y: circleCenter.y + CGFloat(Double(circleRadius) * sin(endAngle/180 * PI))))
        
        let shapeLayer: CAShapeLayer = CAShapeLayer.init()
        shapeLayer.path = path.cgPath
        
        headView = UIView.init(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        headView.center = self.view.center
        headView.backgroundColor = .green
        headView.layer.mask = shapeLayer
        self.view.addSubview(headView)
    }
}
上一篇下一篇

猜你喜欢

热点阅读