Skip to content

Instantly share code, notes, and snippets.

@almaleh
Last active January 17, 2019 01:39
Show Gist options
  • Save almaleh/5799dba8ffa6bf9b7bd6370f7f2f32c0 to your computer and use it in GitHub Desktop.
Save almaleh/5799dba8ffa6bf9b7bd6370f7f2f32c0 to your computer and use it in GitHub Desktop.
Fast CPU-based drawing
class FreedrawingView: UIView {
// we use a multi-dimensional array to store separate lines, otherwise
// all your lines will be connected
var lines = [[CGPoint]]()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// create a new line
lines.append([CGPoint]())
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let newTouchPoint = touches.first?.location(in: self) else { return }
// use `indices` to safetly modify the last element
if let lastIndex = lines.indices.last {
lines[lastIndex].append(newTouchPoint)
}
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(5)
context.setLineCap(.round)
lines.forEach { (line) in
for (index, point) in line.enumerated() {
if index == 0 {
context.move(to: point)
} else {
context.addLine(to: point)
}
}
}
context.strokePath()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment