UIBezierPath实现不规则UIView:
思想:在view上绘制一个封闭的路径然后用layer.mask 遮罩一下就OK
1.先写好图形的顶点(UIBezierPath的各个方法使用在上一篇中有哦)
let cropView = CropViewUseLayer()
cropView.frame = CGRect(x:40,y:80,width:200,height:200)
cropView.backgroundColor = UIColor.yellow
self.view.addSubview(cropView)
let offsetX:CGFloat = 0.0
var modelArray:[LineModel] = []
let model1 = LineModel()
model1.startPoint = CGPoint(x:40+offsetX,y:80)
model1.endPoint = CGPoint(x:140+offsetX,y:80)
let model2 = LineModel()
model2.startPoint = CGPoint(x:140+offsetX,y:80)
model2.endPoint = CGPoint(x:140+offsetX,y:180)
model2.controlPoint = CGPoint(x:90+offsetX,y:130)
model2.lineType = .CurveLine
let model3 = LineModel()
model3.startPoint = CGPoint(x:140+offsetX,y:180)
model3.endPoint = CGPoint(x:40+offsetX,y:180)
let model4 = LineModel()
model4.startPoint = CGPoint(x:40+offsetX,y:180)
model4.endPoint = CGPoint(x:90+offsetX,y:130)
let model5 = LineModel()
model5.startPoint = CGPoint(x:90+offsetX,y:130)
model5.endPoint = CGPoint(x:40+offsetX,y:80)
modelArray.append(model1)
modelArray.append(model2)
modelArray.append(model3)
modelArray.append(model4)
modelArray.append(model5)
cropView.layer.borderColor = UIColor .blue.cgColor
cropView.layer.borderWidth = 2
cropView.lineModelArray = modelArray
cropView.drawLine()
2.调用drawLine方法绘制一下
var lineModelArray:[LineModel] = []
func drawLine() -> Void {
let path = UIBezierPath()
for index in 0...lineModelArray.count-1 {
let model = lineModelArray[index]
if index == 0 {
path.move(to: model.startPoint)
}
if model.lineType == LineType.StraightLine {
path.addLine(to: model.endPoint)
}
else
{
path.addQuadCurve(to: model.endPoint, controlPoint: model.controlPoint)
}
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.frame = self.bounds
self.layer.mask = shapeLayer
let borderLLayer = CAShapeLayer()
borderLLayer.path = path.cgPath
borderLLayer.fillColor = UIColor.green.cgColor
borderLLayer.strokeColor = UIColor.purple.cgColor
borderLLayer.lineWidth = 2.0
self.layer.addSublayer(borderLLayer)
}
其实主要实现就是给CAShapeLayer一个path 让他生成一个不规则的layer 然后把layer传给self.layer.mask 就可以了 ;
注意:
一.shapeLayer.frame = self.bounds 这个frame是相对于UIView的
二. 原以为这个path需要绘制一下移动一下的所以model就那样封装了后来发现这样不行只要第一次move一下就行后面的直接调用addLine不然不能实现
for model in lineModelArray {
path.move(to: model.startPoint)
if model.lineType == LineType.StraightLine {
path.addLine(to: model.endPoint)
}
else
{
path.addQuadCurve(to: model.endPoint, controlPoint: model.controlPoint)
}
}
//这样是不对的哦