2

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.

NeedHelp101
  • 599
  • 1
  • 9
  • 25

2 Answers2

0

What worked for me was placing the PKCanvasView into another UIView then setting the PKCanvasView frame to the scaled image dimensions essentially clipping the view.

Rex
  • 578
  • 5
  • 5
0

I know this question is old , but anyway this is how I did it

      Image("My Image")
          .resizable()
          .scaledToFit()
          .clipped()
          .overlay {
              CanvasView(canvasView: $canvasView, onSaved: saveDrawing)
          }
          .padding(20.0)
Basel
  • 550
  • 8
  • 21