Swift - Using CGContext to draw with finger

后端 未结 3 1162
既然无缘
既然无缘 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-11 05:09

    Hi i make some simple changes and fixed your code, hope it helps someone in the future (code it's updated for Swift 3) :

    class DrawView: UIView {
    
        var touch : UITouch!
        var lineArray : [[CGPoint]] = [[CGPoint]()]
        var index = -1
    
        override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            touch = touches.first! as UITouch
            let lastPoint = touch.location(in: self)
    
            index += 1
            lineArray.append([CGPoint]())
            lineArray[index].append(lastPoint)
        }
    
        override func touchesMoved(_ touches: Set, with event: UIEvent?) {
            touch = touches.first! as UITouch
            let currentPoint = touch.location(in: self)
    
            self.setNeedsDisplay()
    
            lineArray[index].append(currentPoint)
        }
    
        override func draw(_ rect: CGRect) {
    
            if(index >= 0){
                let context = UIGraphicsGetCurrentContext()
                context!.setLineWidth(5)
                context!.setStrokeColor((UIColor(red:0.00, green:0.38, blue:0.83, alpha:1.0)).cgColor)
                context!.setLineCap(.round)
    
                var j = 0
                while( j <= index ){
                    context!.beginPath()
                    var i = 0
                    context?.move(to: lineArray[j][0])
                    while(i < lineArray[j].count){
                        context?.addLine(to: lineArray[j][i])
                        i += 1
                    }
                    context!.strokePath()
                    j += 1
                }
            }
        }
    }
    

提交回复
热议问题