How do I convert or load a UIImage into a PKDrawing?

孤者浪人 提交于 2019-12-21 04:04:25

问题


I'd like to be able to load a PNG file into a PKCanvasView to be able to draw on and erase parts of it. Is there a way to accomplish this?


回答1:


Use setDrawing of PKCanvasView

https://developer.apple.com/documentation/pencilkit/pkcanvasview/3229950-drawing

See 26:53 duration of Session video 221




回答2:


Use an UIImageView and put it behind PKCanvasView, then set the PKCanvasView opaque to false, and color to clear. Draw on it is fine, but erase is not possible.




回答3:


First, put your UIImageView behind PKCanvasView, then set the PKCanvasView opaque to false, and color to clear.

Then in PKCanvasViewDelegate:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return YOUR_IMAGEVIEW
}

func scrollViewDidZoom(_ scrollView: UIScrollView) {

    let offsetX: CGFloat = max((scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5, 0.0)
    let offsetY: CGFloat = max((scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5, 0.0)
    YOUR_IMAGEVIEW.frame.size = CGSize(width: self.view.bounds.width * scrollView.zoomScale, height: self.view.bounds.height * scrollView.zoomScale)
    YOUR_IMAGEVIEW.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)

}

As apple said, putting your imageView in viewForZooming is enough, but It doesn't work. So I added above codes in scrollViewDidZoom and it just works as it is supposed to be.



来源:https://stackoverflow.com/questions/56573180/how-do-i-convert-or-load-a-uiimage-into-a-pkdrawing

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