Free Drawing On UIImage Embedded in UIScrollView

雨燕双飞 提交于 2019-12-09 23:27:35

问题


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)
}

来源:https://stackoverflow.com/questions/41005210/free-drawing-on-uiimage-embedded-in-uiscrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!