与Android类似,绘制过程需要重写draw(_ rect:CGRect)方法
class CustomUIView:UIView{
override func draw(_ rect:CGRect){
//上下文对象:可以理解为具体的设备对象,比如IOS设备,MacOS设备,PDF等
let context = UIGraphicsGetCurrentContext()
//设置线段属性
setLineProperties(context)
//绘制直线
drawLine(context)
//绘制虚线
drawDashLine(context)
//绘制椭圆
drawEllipse(context)
//绘制圆形
drawCircle(context)
//绘制弧线
drawArc(context)
//绘制矩形
drawRect(context)
//绘制路径
drawPath(context)
//裁剪区域
clipArea(context)
}
}
绘制方法
extension CustomUIView{
private func setLineProperties(_ context:CGContext?){
//设置线段相关属性
context?.setLineJoin(.round)
context?.setStrokeColor(UIColor.red.cgColor)
context?.setLineWidth(2)
context?.setLineCap(CGLineCap.square)
}
private func drawLine(_ context:CGContext?){
//将起始点移动到原点
context?.move(to: CGPoint(x: 0, y: 0))
//此函数以当前点为startPoint,连接线段到终点(endPoint)
context?.addLine(to: CGPoint(x: 50, y: 50))
//调用这个函数才能真正绘制出线段
context?.strokePath()
}
private func drawArc(_ context:CGContext?){
//参数分别为:center(圆心),radius(半径),startAngle(开始角度:以弧度表示),endAngle(结束角度:以弧度表示),clockwise(true为顺时针圆弧,false为逆时针圆弧)
let center = CGPoint(x: bounds.width/2, y: bounds.height/2)
let radius = bounds.width/2
let startAngle = CGFloat(90).asRad()
let endAngle = CGFloat(180).asRad()
print("endAngle = \(endAngle)")
let clockwise = false
context?.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
context?.strokePath()
}
private func drawRect(_ context:CGContext?){
let rect = CGRect(x: 70, y: 50, width: 100, height: 50)
context?.addRect(rect)
context?.strokePath()
}
}
因为drawArc参数是弧度,所以这里扩展一下CGFloat方法,支持弧度输出
extension CGFloat{
//转成弧度
func asRad() -> CGFloat{
return self * CGFloat.pi / 180
}
}
触摸手势处理
//MARK:重写触摸拦截
extension CustomUIView{
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touchesBegan")
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touchesMoved")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touchesEnded")
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touchesCancelled")
}
}