Rendering PDF in iOS using drawRect and drawLayerI

2019-08-30 06:36发布

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 .

1条回答
老娘就宠你
2楼-- · 2019-08-30 06:58

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

查看更多
登录 后发表回答