Skip to content

Instantly share code, notes, and snippets.

@almaleh
Last active July 16, 2023 05:45
Show Gist options
  • Save almaleh/a4d6ad95ad492b55874faa1b867a2407 to your computer and use it in GitHub Desktop.
Save almaleh/a4d6ad95ad492b55874faa1b867a2407 to your computer and use it in GitHub Desktop.
Slow CPU-based Drawing
class FreedrawingImageViewCG: UIImageView {
var currentTouchPosition: CGPoint?
override func layoutSubviews() {
super.layoutSubviews()
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let newTouchPoint = touches.first?.location(in: self) else { return }
currentTouchPosition = newTouchPoint
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let newTouchPoint = touches.first?.location(in: self) else { return }
guard let previousTouchPoint = currentTouchPosition else { return }
let renderer = UIGraphicsImageRenderer(size: bounds.size)
image = renderer.image { ctx in
image?.draw(in: bounds)
UIColor.red.setStroke()
ctx.cgContext.setLineCap(.round)
ctx.cgContext.setLineWidth(5)
ctx.cgContext.move(to: previousTouchPoint)
ctx.cgContext.addLine(to: newTouchPoint)
ctx.cgContext.strokePath()
}
currentTouchPosition = newTouchPoint
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
currentTouchPosition = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment