0

I'm trying to share my PKDrawing results via PDF file for email or print. I'm creating the PDF using 2 other PDF files plus the PKDrawing on the top layer. The 2 PDF layers look clear. The PKDrawing however is somewhat grainy, especially compared to a printed screen shot.

Here's my current code:

UIGraphicsBeginPDFContextToFile(filePath, CGRect.zero, nil)
    
var drawing: PKDrawing = PKDrawing.init()
let markup: Data = self.pages![pagenum].value(forKey: "markup") as! Data
let drawingHeight = self.pages![pagenum].value(forKey: "height") as! CGFloat
let drawingWidth = self.pages![pagenum].value(forKey: "width") as! CGFloat
            
do {
    try drawing = PKDrawing.init(data: markup)
} catch {
    print("Error loading drawing") 
}

let pageSize = CGSize(width: 0, height: 0)
//let scale: CGFloat = 2.0    THIS VALUE DOESN'T SEEM TO MATTER 
let scale: CGFloat = 1.0 

if landscapeOrientation {
    pageSize = CGSize(width:2048, height: 1408)
} else {
    pageSize = CGSize(width: 1536, height: 1920)
}
                
let canvas = PKCanvasView(frame: CGRect(x: 0.0, y: 0.0, width: drawingWidth, height: drawingHeight))
canvas.drawing = drawing
markupImage = drawing.image(from: canvas.frame, scale: scale)
if pageSize.width != drawingWidth {
   canvas.drawing.transform(using: CGAffineTransform(scaleX: pageSize.width / drawingWidth, y: pageSize.height / drawingHeight))
}
//markupImage = drawing.image(from: canvas.frame, scale: self.view.contentScaleFactor)  THIS CHANGE MADE A BIG DIFFERENCE 
markupImage = drawing.image(from: canvas.frame, scale: 4.0) 
                
UIGraphicsBeginImageContext(pageSize)
backgroundView?.draw(in: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: pageSize))
templateView?.draw(in: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: pageSize))
            
markupImage.draw(in: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: pageSize))
          
let pdfImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
        
let pageRect: CGRect = CGRect(origin: CGPoint.zero, size: pageSize)
UIGraphicsBeginPDFPageWithInfo(pageRect, nil)
let pdfContext: CGContext = UIGraphicsGetCurrentContext()!
pdfContext.scaleBy(x: 1.0, y: 1.0)
pdfImage.draw(at: CGPoint(x: 0.0, y: 0.0))
        
UIGraphicsEndPDFContext()
David Peat
  • 244
  • 2
  • 5

1 Answers1

1

Changing my scale from 2.0 to 4.0 cleared it up quite a bit, I hadn't thought to try that. Will edit the code with my change and a comment. Definitely open for other alternatives though if there's a cleaner or clearer way to do this. I'm not the best at resolutions / pixel spaces.

David Peat
  • 244
  • 2
  • 5