I'm working on a simple freehand drawing app. Below is the sample code, I'm using the UIGesture class to track the scribble, i.e., pencil or finger movement, and then stroking those touch points on the UIImageView, the stroke edges are blurry hence I scaled the context between 4 - 8, which gives strokes sharp edges. But however, this severely affects the smoothness of writing/lags extremely because strokes are scaled. How to reduce this lag?
class CanvasView: UIImageView, UIGestureRecognizer {
var drawingImage: UIImage?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5)
let context = UIGraphicsGetCurrentContext()
drawingImage?.drawAsPattern(in: bounds)
var touches = [UITouch]()
if let coalescedTouches = event.coalescedTouches(for: touch) {
touches = coalescedTouches
} else {
touches.append(touch)
}
for touch in touches {
drawStroke(context: context, touch: touch)
}
drawingImage = UIGraphicsGetImageFromCurrentImageContext()
if let predictedTouches = event.predictedTouches(for: touch) {
for touch in predictedTouches {
drawStroke(context: context, touch: touch)
}
}
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func drawStroke(context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocation(in: self)
let location = touch.location(in: self)
var lineWidth: CGFloat = 3
UIColor.black.setStroke()
context?.setLineWidth(lineWidth)
context?.setLineCap(.round)
context?.move(to: previousLocation)
context?.addLine(to: location)
context?.strokePath()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
image = drawingImage
}}