0

I have a custom class for stamp annotation with an image.

While adding the annotation to a rotated PDF page, the annotation also rotating.

To prevent this rotation and to make an upright stamp I'm rotating the context.

But the image is not drawing properly.

class PDFImageAnnotation: PDFAnnotation {
static let nameValue = "validSignature"
var image: UIImage?
var isFromText = false
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) {
    guard let cgImage = image?.cgImage else { return }
    context.setFillColor(UIColor.red.cgColor)
    context.fill(bounds)
    //context.clear(bounds)
    
    let size = CGSize(width: bounds.width - 5, height: bounds.height - 5)
    let rect = CGRect(origin: bounds.origin, size: size)
    var boundsToDraw = isFromText ? bounds : rect
    
    let rotation = CGFloat(page!.rotation % 360) * CGFloat.pi / 180
    var transform = CGAffineTransform.identity
    // First translate and go to the center of the stamp annotation
    transform = transform.translatedBy(x: boundsToDraw.origin.x  + (boundsToDraw.size.width / 2),
                                       y: boundsToDraw.origin.y + (boundsToDraw.size.height / 2))
    // Now rotate the context in the opposite direction of the page rotation
    transform = transform.rotated(by:  rotation)
    // Translate back to origin
    transform = transform.translatedBy(x: -1 * (boundsToDraw.origin.x + (boundsToDraw.size.width / 2) ),
                                       y: -1 * (boundsToDraw.origin.y + (boundsToDraw.size.height / 2)))
    context.concatenate(transform)

    context.draw(cgImage, in: boundsToDraw)
}

}

To identify the context frame, background color is given red.

Before adding as an annotation Before adding as an annotation After adding as an annotation After adding as an annotation

Yasheed Mohammed
  • 187
  • 1
  • 14

0 Answers0