效果:
基本代码:
// DrawingBoard 画板
class DrawingBoard: UIView {
/// 线宽
var lineWidth:CGFloat = 5.0
/// 线条颜色
var lineColor:UIColor? = nil
// 存储路径
lazy var paths:[HBPath] = {return []}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
for line in paths{
line.drawPath()
}
}
func getTouches(touches:Set<UITouch>) -> CGPoint {
return (touches.first?.location(in: self))!
}
// 开始画线
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = getTouches(touches: touches)
let path = HBPath.path(beginPoint: point, pathWidth: lineWidth, isEraser: isEraser)
path.pathColor = lineColor
paths.append(path)
setNeedsDisplay()
}
/// 正在画线
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = getTouches(touches: touches)
let path = paths.last
path?.bezierPath?.addLine(to: point)
setNeedsDisplay()
}
/// 结束画线
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesMoved(touches, with: event)
}
}
// Path 线条
class Path: NSObject {
var bezierPath:UIBezierPath?
var beginPoint:CGPoint?
var pathWidth:CGFloat?
var pathColor:UIColor?
class func path(beginPoint:CGPoint,pathWidth:CGFloat,isEraser:Bool)->HBPath{
let path = HBPath()
path.beginPoint = beginPoint
path.pathWidth = pathWidth
path.isEraser = isEraser
let bezier = UIBezierPath()
bezier.lineCapStyle = CGLineCap.round
bezier.lineJoinStyle = CGLineJoin.round
bezier.lineWidth = pathWidth
bezier.move(to: beginPoint)
path.bezierPath = bezier
return path
}
func drawPath() {
pathColor?.set()
bezierPath?.stroke()
}
}
// 其他功能后续完善!