I would just like some sample code for a view that you can draw on in the current version of swift. I have looked through a few tutorials and the only one I can find that works looks like the code below. I dont want to use this implementation because it is redrawing the entire image from scratch each time I move my finger, meaning it gets very slow as the image I am drawing becomes more complex. Could someone point me in the direction or give me an idea of how it should be done? Thank you!
import UIKit
class DrawingView : UIView {
private class Line {
var startPont : CGPoint
var endPoint : CGPoint
init(start : CGPoint, end : CGPoint) {
startPont = start
endPoint = end
}
}
var lastPoint : CGPoint!
private var lines = [Line]()
var tempImage : UIImageView! = UIImageView()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
lastPoint = touch.location(in: self)
lines.append(Line(start: lastPoint, end: lastPoint))
self.setNeedsDisplay()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let newPoint = touch.location(in: self)
lines.append(Line(start: lastPoint, end: newPoint))
lastPoint = newPoint
self.setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
for line in lines {
context?.beginPath()
context?.move(to: line.startPont)
context?.addLine(to: line.endPoint)
context?.setLineCap(CGLineCap.round)
context?.setFillColor(UIColor.black.cgColor)
context?.setStrokeColor(UIColor.black.cgColor)
context?.setLineWidth(8.0)
context?.strokePath()
}
}
func clear() {
lines = [Line]()
self.setNeedsDisplay()
}
}