I like to make PKCanvasView
to be scrollable and zoomable with underlay image. It seems it is okay to make it scrollable and zoomable without underlaying background image. But to make it with underlaying image I don’t know how to make it work.
Since PKCanvasView
is a subclass of UIScrollView
, I tried place custom content UIView
within scroll view, then set a delegate to specify that view for zooming. But PKCanvasView
’s drawing image and content view will not synchronize their positions when zooming, it’s okay with scrolling.
+ UIView (root view)
+ PKCanvasView
+ Custom UIView (underlaying image drawing)
Then I tried PKCanvasView
as just a content view within another UIScrollView
, treat PKCanvasView
as non-scrollable view. Then I synchronize the positions between PKCanvasView
’s drawing and container drawing image. However, I am not sure whether, PKCanvasView
may not be designed for being under another UIScrollView
, behavior of positioning ruler by finger isn’t stable, kept jumping place to place by dragging.
+ UIView (root view)
+ UIScrollView
+ Custom UIView (underlaying image drawing)
+ PKCanvasView
As far as I know, most of PKCanvasView
sample code work well without zooming with underlaying image. But once I set to maximumZoomScale
to 2 or more. Then it no longer synchronize drawings and underlaying background image.
Thanks
Set up your PKCanvasView
in Main.storyboard
and link it to your ViewController
(@IBOutlet weak var canvasView: PKCanvasView!
) and adjust the following property (in your Main.storyboard
or viewDidLoad()
for the ViewController
):
canvasView.isOpaque = false
Create also a custom UIView view
in your viewDidLoad()
and add it to your PKCanvasView
:
canvasView.insertSubview(view, at: 0)
It's important that you insert it at 0, so it will be behind your drawings.
Create a new function didZoom(to scale: CGFloat)
in an Extension of UIView
or if you created a Subclass, add it there. There you can adjust your view to the new scale.
In your ViewController
add a function like updateContentSizeForDrawing()
:
func updateContentSizeForDrawing() {
view.frame.size = canvasView.contentSize
view.didZoom(to: canvasView.zoomScale)
}
I recommend to call this function at the end of your viewWillAppear()
. To observe when the user zooms, add the delegate function to your ViewController
:
func scrollViewDidZoom(_ scrollView: UIScrollView) {
updateContentSizeForDrawing()
}
I kept googling again, and I found a clue for this problem. Since, I cannot read Chinese, but I can read the code piece.
https://stackoom.com/question/3pNGe/如何将UIImage转换或加载到PKDrawing中
I was experimenting on this for a while, and I post the project to GitHub.
https://github.com/codelynx/PKCanvasViewTester
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With