How to correctly resize PKDrawing when layout changes?
Asked Answered
N

0

7

I'm trying to layer a PKCanvasView on top of an image, which works fine with the initial layout but when the view is resized (by rotating the iPad) the PKDrawing within is not scaled which results in the image annotations being in the incorrect place. I'm struggling to work out how to correctly scale the PKDrawing to preserve the correct positions.

An example showing the misplacement of my initial drawing

This is an example demonstrating the issue:

class ImageDrawingView: UIView {

    private let imageView = UIImageView(frame: .zero)
    private let drawingView = PKCanvasView(frame: .zero)
    private let toolPicker = PKToolPicker()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {
        // Setup image view
        addSubview(imageView)
        imageView.image = UIImage(named: "TestImage") // Here I just used a screen grab of the lock screen
        imageView.contentMode = .scaleAspectFill

        // Setup drawing view
        addSubview(drawingView)
        drawingView.isOpaque = false
        toolPicker.setVisible(true, forFirstResponder: drawingView)
        toolPicker.addObserver(drawingView)
        drawingView.becomeFirstResponder()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        imageView.frame = bounds
        drawingView.frame = bounds
    }
}

class ViewController: UIViewController {

    private let imageDrawingView = ImageDrawingView(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageDrawingView)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        imageDrawingView.frame = view.bounds
    }
}

I think if I can calculate the transform, I can then use drawingView.drawing.transform(using: transformScale). How do I go about calculating the transform please?

Nippur answered 25/4, 2021 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.