Last active
January 16, 2019 04:49
-
-
Save almaleh/5c796b05cab9164a1449fa0cf8947593 to your computer and use it in GitHub Desktop.
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
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