Search code examples
iosswiftxcodeios-pdfkitapple-pdfkit

How to annotate rounded, aspect-fill image in PDFView (swift PDFKit)


I am working on annotate an image to an existing PDFView. This is my current state: enter image description here

And below is my desired state: enter image description here

In one sentence, I want to achieve:

  1. a rounded corder of my image annotation
  2. image should also maintain the original aspect ratio I have tried and searched many sources but none of them works.

Below is my current code:

class PDFImageAnnotation: PDFAnnotation {

var image: UIImage?

convenience init(_ image: UIImage?, bounds: CGRect, properties: [AnyHashable : Any]?) {
    self.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp, withProperties: properties)
    self.image = image
}

override func draw(with box: PDFDisplayBox, in context: CGContext) {
    super.draw(with: box, in: context)

    // Drawing the image within the annotation's bounds.
    guard let cgImage = image?.cgImage else { return }
    context.draw(cgImage, in: bounds)
}

}

Implementation in ViewDidLoad:

if let image = pet.picture?.getImage() {
        let imageAnnotation = PDFImageAnnotation(image, bounds: CGRect(x: 80, y: 1100, width: 300, height: 300), properties: nil)
        pdfView.currentPage?.addAnnotation(imageAnnotation)
    }

Any suggestion would be helpful because I'm at a dead end right now, thank you so much!


Solution

  • Ok I figured it out, it turns out I should first clip the image to rounded format then annotate that to the PDF, using this extension: https://stackoverflow.com/a/64981764/11079192