1

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
}}
Raj Kiran
  • 152
  • 1
  • 9
  • hi, perhaps might be of interest https://stackoverflow.com/questions/15370344/painfully-slow-software-vectors-particularly-coregraphics-vs-opengl – jspcal Feb 06 '23 at 19:31
  • @jspcal I checked a few of the comments and answers, and I could reduce lag a little but not to a great extent. – Raj Kiran Feb 08 '23 at 17:46

0 Answers0