Free Drawing On UIImage Embedded in UIScrollView

2019-04-16 06:28发布

问题:

I am working on project that involves drawing freehand on a UIImage inside a UIScrollView. Everything works fine with the drawing at default zoom, however if I adjust the zoom of the UIScrollView and try drawing again, it starts to distort the image by shrinking it and making the image appear blurry. It also pushes the images to the far left-right of the screen. I have tried using different scaling options to no avail.

Here is the image at normal scale with some drawing in it.

Here is the image after zooming and drawing for a few seconds

Here is the relevant code (methods are declared in the view controller that contains the scroll view

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)              
    let currentPoint = touches.first!.location(in: drawingImageView) 
    UIGraphicsBeginImageContextWithOptions(drawingImageView.frame.size, false, 0)
    drawingImageView.image?.draw(in: CGRect(x: 0, y: 0, width: drawingImageView.frame.size.width, height: drawingImageView.frame.size.height))

    UIGraphicsGetCurrentContext()?.addRect(CGRect(x: currentPoint.x, y: currentPoint.y, width: 1, height: 1))
    UIGraphicsGetCurrentContext()?.setLineCap(.round)
    UIGraphicsGetCurrentContext()?.setLineWidth(10)
    UIGraphicsGetCurrentContext()?.setStrokeColor(colorSelectorButton.backgroundColor!.cgColor)
    UIGraphicsGetCurrentContext()?.setBlendMode(.normal)
    UIGraphicsGetCurrentContext()?.strokePath()
    drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
}