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.
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?