iosswiftxcodepencilkit

Scale PencilKit Drawing to Fit Canvas size


I have a PKCanvasView in my IOS app. When the user puts in a drawing, it saves the strokes as a PKDrawing. This drawing could be accessed on many different devices with different screen sizes. However, when a drawing that is created on a larger device, eg, an iPad, is viewed on a smaller device, eg, an iPhone, the drawing is cut off from the bottom right. Additionally, when a drawing created on a smaller device is viewed on the bigger device, it does not fill the space but rather is confined to the top right corner.

My Question: Is there any way to scale a PKDrawing up or down to fit the PKCanvasView's frame?


Solution

  • I fixed it by using the transform function to scale the drawing up or down to fit the screen size. I made an extension:

    extension PKDrawing {
        mutating func scale(in frame: CGRect) {
            var scaleFactor:CGFloat = 0
            
            if self.bounds.width != frame.width {
                scaleFactor = frame.width / self.bounds.width
            } else if self.bounds.height != frame.height {
                scaleFactor = frame.height / self.bounds.height
            }
            
            let trasform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
            
            self.transform(using: trasform)
        }
    }