-
-
Save WallabyStuff/bba6de56f53792260bc839ab32351a91 to your computer and use it in GitHub Desktop.
Slow 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 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