Swift - Using CGContext to draw with finger

后端 未结 3 1175
既然无缘
既然无缘 2021-02-11 04:06

I\'m trying to make a drawing app. I have a single custom UIView:

class DrawView: UIView {

var touch : UITouch!
var lastPoint : CGPoint!
var currentPoint : CGPo         


        
3条回答
  •  时光取名叫无心
    2021-02-11 05:03

    marcomoreira92 and Keuha's version worked for me, but I don't like to use indices that much. Thus here is an alternative version, which was tested in Swift 4.2:

    class DrawView: UIView {
    
        var lineArray: [[CGPoint]] = [[CGPoint]]()
    
        override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            guard let touch = touches.first else { return }
            let firstPoint = touch.location(in: self)
            lineArray.append([CGPoint]())
            lineArray[lineArray.count - 1].append(firstPoint)
        }
    
        override func touchesMoved(_ touches: Set, with event: UIEvent?) {
            guard let touch = touches.first else { return }
            let currentPoint = touch.location(in: self)
            lineArray[lineArray.count - 1].append(currentPoint)
            setNeedsDisplay()
        }
    
        override func draw(_ rect: CGRect) {
            let context = UIGraphicsGetCurrentContext()
            context?.setLineWidth(5)
            context?.setStrokeColor(UIColor.black.cgColor)
            context?.setLineCap(.round)
    
            for line in lineArray {
                guard let firstPoint = line.first else { continue }
                context?.beginPath()
                context?.move(to: firstPoint)
                for point in line.dropFirst() {
                    context?.addLine(to: point)
                }
                context?.strokePath()
            }
        }
    }
    

提交回复
热议问题