class CircleView: UIView {
override func draw(_rect:CGRect) {
//1.添加设计师提供一张渐变色图
let imageView =UIImageView(image:UIImage.init(named:"gradient_image"))
imageView.frame=self.bounds
self.addSubview(imageView)
//2.画贝塞尔曲线,例如画弧形
let path = UIBezierPath(arcCenter: CGPoint(x: self.bounds.size.width * 0.5, y: self.bounds.size.height * 0.5),
radius:UIScreen.main.bounds.size.width*0.17,
startAngle:0.0,
endAngle:CGFloat(2.0* .pi),
clockwise:true)
path.lineWidth=60
//3.新建CAShapeLayer
let shapeLayer =CAShapeLayer()
shapeLayer.frame=self.bounds
shapeLayer.position=CGPoint(x:self.bounds.size.width*0.5,y:self.bounds.size.height*0.5)
shapeLayer.path= path.cgPath
shapeLayer.fillColor=UIColor.clear.cgColor
shapeLayer.strokeColor=UIColor.white.cgColor
shapeLayer.lineWidth= path.lineWidth
//4.设置 第1步的图片的蒙版为第3步的CAShapeLayer
self.layer.mask= shapeLayer
}
}
和oc版本基本一致,只是语法略微不同,涉及的相关图片见 渐变色饼图 - OC版