iOS中提供了一个非常好的PDF解析类库,可以很方便地使用CGPDFDocumentRef读取PDF文件内容。但是由于PDF文件一般尺寸都比较大,一次性把内容展示出来,比较占内存。为了优化展示而不浪费不必要的内存消耗,可以使用视图UIView的CALayer机制,可以使用 CATiledLayer把PDF页面分成好几个区域,展示哪个区域就调用哪个区域的数据,可以大大节省内存开销。对大尺寸的图像,也可以使用这种原理来处理。
首先使用CGPDFDocumentRef读取PDF文件,使用CGPDFDocumentGetPage方法获取到指定页的CGPDFPageRef。
下面提供这个思路的主要代码片段:
01 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
02 {
03 CGPDFPageRef pageRef = myPageRef
04 if (pageRef != nil && ctx != nil) {
05 [(NSObject*)pageRef retain];
06 //prevent releasing while drawing
07 CGPDFPageRetain(pageRef);
08 CGContextRetain(ctx);
09 CGContextSaveGState(ctx);
10
11 CGRect bounding = layer.bounds;
12 CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
13 CGContextFillRect(ctx, CGContextGetClipBoundingBox(ctx));
14 CGContextTranslateCTM(ctx, 0.0, bounding.size.height);
15 CGContextScaleCTM(ctx, 1.0, -1.0);
16 CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(pageRef, kCGPDFCropBox, bounding, 0, true));
17 CGContextDrawPDFPage(ctx, pageRef);
18 CGContextRestoreGState(ctx);
19 CGContextRelease(ctx);
20 CGPDFPageRelease(pageRef);
21 [(NSObject*)pageRef release];
22 }
23
24 }
以上代码就显示出PDF内容了。
继续完善以上代码。
由于PDF读取一般速度比较慢,因此用户会有一个等待的时间,此时屏幕就会显示空白,为了弥补这个不好看的效果,可以考虑在展示层CALayer后增加一个背景图片CALayer。
1 //设置背景层
2 self.imageLayer = [CALayer layer];
3 //设置层的图像
4 self.imageLayer.contents = (id) yourUIImage.CGImage;
5 //将背景层添加到视图中去
6 [self.layer addSublayer:self.imageLayer];
另外,由于显示PDF的速度也不一定很快,尤其在切换PDF页面时。其实展示PDF最终希望是能够看清楚内容,如果缩放的比例大小,看不清内容的话,这种展示对用户来说也没有多少实际意义。因此可以利用这点做一些技巧性的优化,当PDF缩放比例太小时,就不要显示真正的PDF内容,而显示一个自己的图像,或者页面缩略图也行。优化上面方法drawLayer:的代码:
01 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
02
03 {
04 if(self.zoomScale < 2.0 ){
05 CGImageRef cgImage = yourUIImage.CGImage;
06 if( cgImage != nil )
07 {
08 CGContextSaveGState( context );
09 CGRect bounding = self.bounds;
10 CGContextTranslateCTM(ctx, 0.0, bounding.size.height);
11 CGContextScaleCTM(ctx, 1.0, -1.0);
12 CGContextDrawImage( context, bounding, cgImage );
13 CGContextRestoreGState( context );
14 }
15 }else {
16 CGPDFPageRef pageRef = myPageRef
17 …
18 }
19 }