Last active
January 17, 2019 01:39
-
-
Save almaleh/5799dba8ffa6bf9b7bd6370f7f2f32c0 to your computer and use it in GitHub Desktop.
Fast CPU-based drawing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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