之前在网上查阅了很多资料,大多博客或者论坛都只给出了如何读取的API及代码,如下:
-(void)drawInContext:(CGContextRef)context
{
// PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system
// before we start drawing.
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
// We’re about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing
CGContextSaveGState(context);
// CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any
// base rotations necessary to display the PDF page correctly.
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
// Finally, we draw the page and restore the graphics state for further manipulations!
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect {
[self drawInContext:UIGraphicsGetCurrentContext()];
}
但是,在此需要提醒注意的是:此代码仅能在第一次的时候运行成功,但是如果在进行翻页的时候则可能会出现invaild context 问题,原因则在于,上下文只在绘制UIView时会生成,而当UIView绘制成功之后,再调用UIGraphicsGetCurrentContext() 则获取不到有效上下文,所以需要在适当位置调用以下
API方法:setNeedsDisplay;