Drawing a PDF Right-Side-Up in CGContext
cocoa, cocoa-touch, iphone, objective-c
Solution
Try doing the translate before the scale:
CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
Problem
I'm overriding the drawRect: method in a custom UIView, and I'm doing some custom drawing. All was going well, until I needed to draw a PDF resource (a vector glyph, to be precise) into the context. First I retrieve the PDF from a file: ``` NSURL *pdfURL = [NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CardKit.bundle/A.pdf"]]; CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL); CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1); ``` Then I create a box with the same dimensions as the loaded PDF: ``` CGRect box = CGPDFPageGetBoxRect(pdfPage, kCGPDFArtBox); ``` Then I save my graphics state, so that I don't screw anything up: ``` CGContextSaveGState(context); ``` And then I perform a scale+translate of the CTM, theoretically flipping the whole context: ``` CGContextScaleCTM(context, 1.0, -1.0); CGContextTranslateCTM(context, 0.0, rect.size.height); ``` I then scale the PDF so that it fits into the view properly: ``` CGContextScaleCTM(context, rect.size.width/box.size.width, rect.size.height/box.size.height); ``` And finally, I draw the PDF and restore the graphics state: ``` CGContextDrawPDFPage(context, pdfPage); CGContextRestoreGState(context); ``` The issue is that there is nothing visible drawn. All this code should theoretically draw the PDF glyph into the view, right? If I remove the scale+translate used to flip the context, it draws perfectly: it just draws upside-down. Any ideas?