Skip to content

Instantly share code, notes, and snippets.

@almaleh
Last active January 16, 2019 04:49
Show Gist options
  • Save almaleh/5c796b05cab9164a1449fa0cf8947593 to your computer and use it in GitHub Desktop.
Save almaleh/5c796b05cab9164a1449fa0cf8947593 to your computer and use it in GitHub Desktop.
var flattenedImage: UIImage?
var line = [CGPoint]() {
didSet {
checkIfTooManyPointsIn(&line)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
flattenImage()
}
// called when adding new points
func checkIfTooManyPointsIn(_ line: inout [CGPoint]) {
let maxPoints = 200
if line.count > maxPoints {
flattenedImage = self.getImageRepresentation()
// we leave one point to ensure no gaps in drawing
_ = line.removeFirst(maxPoints - 1)
}
}
// called from touches ended
func flattenImage() {
flattenedImage = self.getImageRepresentation()
line.removeAll()
}
// convert view to bitmap
func getImageRepresentation() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment