How to prevent drawing outside the scaled aspect ratio image background?
I need to draw on images, similar to markup, and based on what I've seen, you have to add an image to the background of a PKCanvasView.
In the SO below, I more or less did the same. However, my device and image sizes aren't identical.
PencilKit Code similar to this one
struct MyCanvas: UIViewRepresentable {
var canvasView: PKCanvasView
let picker = PKToolPicker.init()
func makeUIView(context: Context) -> PKCanvasView {
self.canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
self.canvasView.isOpaque = false
self.canvasView.backgroundColor = UIColor.clear
self.canvasView.becomeFirstResponder()
let imageView = Image("badmintoncourt")
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
let subView = self.canvasView.subviews[0]
subView.addSubview(imageView)
subView.sendSubviewToBack(imageView)
return canvasView
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
picker.addObserver(canvasView)
picker.setVisible(true, forFirstResponder: uiView)
}
}
My screen size is : (1194.0, 790.0), whlist the image size is (1668.0, 2348.0). Despite the image view having an aspect ratio fit, it doesn't automatically scale.
To fix this I got used Geometry reader and passed in the screen width/height, then set the ImageView's frame, this now scaled images accordingly.
The problem is that I can draw outside the image bounds, with a vertical image, viewed horizontally, there's plenty of white space to the left and right of the image. I don't want to be able to draw there.
Is there anyway of setting the drawable canvas to the same as the scaled image?
Another problem would be when I change device orientation, the drawings don't stick to the image like using Apple's "Markup" does. I read a bit and seems like anchors might work? Unsure how to use them though.
question from:
https://stackoverflow.com/questions/65838064/set-pencilkit-canvas-to-be-the-input-image-size-and-prevent-drawing-outside-that 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…