Swift - Free Draw

Programming/Swift 2017.07.01 09:46 Posted by 파란크리스마스

출처 : Freehand drawing on iOS in Swift - Ilya Puchka


    override func touchesBegan(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesBegan"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lastPoint = touch.location(in: drawImageView)
        }
    }
    
    override func touchesMoved(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesMoved"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lineWidth = CGFloat(Int(textLineWidth.text!)!);
            
            UIGraphicsBeginImageContext(drawImageView.frame.size)
            if let context = UIGraphicsGetCurrentContext() {
                context.setLineWidth(lineWidth)
                context.setStrokeColor(lineColor)
                context.setLineCap(CGLineCap.round)
                
                drawImageView.image?.draw(in: CGRect(origin: CGPoint(x : 0, y : 0), size: drawImageView.frame.size))
                
                context.move(to: lastPoint)
                let currentPoint = touch.location(in: drawImageView)
                context.addLine(to : currentPoint)
                context.strokePath()
                
                drawImageView.image = UIGraphicsGetImageFromCurrentImageContext()
                
                lastPoint = currentPoint
            }
            UIGraphicsEndImageContext()
        }
    }

    override func touchesEnded(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesEnded"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
        }
    }




 

티스토리 툴바