iOS_DrawView_画板01_Swift

效果:


基本代码:

// 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()
    }
}

// 其他功能后续完善!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值