简体   繁体   中英

Rendering PDF in iOS using drawRect and drawLayerInContext

I'm creating a custom view that renders a PDF to its bounds rectangle .
I have pasted the code below :

CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context, self.bounds);

CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGFloat scale = MIN(self.bounds.size.width / pageRect.size.width, self.bounds.size.height / pageRect.size.height);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextScaleCTM(context, scale, scale);    
CGContextDrawPDFPage(context, self.page);
CGContextRestoreGState(context);

My question is , if I use the above code in the drawRect method it just gives me a black rectangle . If I use it in the drawLayer: inContext: method it works fine . What could be the reason ?

PS : When using it drawRect I use the method UIGraphicsGetCurrentContext() to get the current graphics context .

This code actually works fine for me .. Add breakpoint and check it hits the -drawrect method

 CGContextRef context = UIGraphicsGetCurrentContext();
NSString *filePath = [[NSBundle mainBundle]
                      pathForResource:@"Trial" ofType:@"pdf"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath];
CGPDFDocumentRef document = [self openDocument:(CFURLRef)url];
[url release];

CGPDFPageRef docPageRef =CGPDFDocumentGetPage(document, 1);

CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context, self.bounds);

CGRect pageRect = CGPDFPageGetBoxRect(docPageRef, kCGPDFMediaBox);
CGFloat scale = MIN(self.bounds.size.width / pageRect.size.width, self.bounds.size.height / pageRect.size.height);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextScaleCTM(context, scale, scale);
CGContextDrawPDFPage(context, docPageRef);
CGContextRestoreGState(context);

I used this in my drawrect and it worked fine.

Check all the references are getting the value that you are providing to the drawrect check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM