簡介
這裏介紹兩種方法顯示PDF,第一種用UIWebView,特色是代碼簡單,可是無法實現翻頁效果。第二中方法利用IOS系統的CGContextDrawPDFPage方法手動實現,代碼複雜一些,同時須要配合UIScrollView實現縮放,以及利用UIPageViewController實現翻頁的效果。git
方法一:利用UIWebView
1
2 3 4 5 6 |
-(void)loadPDF:(NSString*)fileName inWebView:(UIWebView*)webView{ NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; } |
- 技巧:設置
webView.scalesPageToFit = YES;
能夠實現pinch放大縮小 - 缺點:沒有翻頁的動畫效果
方法二:利用CGContextDrawPDFPage
CGContextDrawPDFPage
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
-(void)drawInContext:(CGContextRef)context atPageNo:(int)page_no{ // 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); if (pageNO == 0) { pageNO = 1; } CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, pageNO); CGContextSaveGState(context); { CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true); CGContextConcatCTM(context, pdfTransform); CGContextDrawPDFPage(context, page); } CGContextRestoreGState(context); } |
須要先反轉座標,根據pageNO獲取到CGPDFDocumentRef的那一頁,直接CGContextDrawPDFPage。github
UIScrollView
配合UIScrollView實現縮放,ZPDFPageController的主要代碼:web
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
-(void)viewDidLoad{ [super viewDidLoad]; UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds]; scrollView.showsVerticalScrollIndicator=NO; scrollView.showsHorizontalScrollIndicator=NO; scrollView.minimumZoomScale=1.0f; scrollView.maximumZoomScale=3.0f; scrollView.delegate=self; [self.view addSubview:scrollView]; pdfView = [[ZPDFView alloc] initWithFrame:scrollView.bounds atPage:(int)self.pageNO withPDFDoc:self.pdfDocument]; pdfView.backgroundColor=[UIColor whiteColor]; [scrollView addSubview:pdfView]; scrollView.contentSize=pdfView.bounds.size; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{ return pdfView; } |
UIPageViewController
UIPageViewController的TransitionStyle設置爲UIPageViewControllerTransitionStylePageCurl(翻頁)。其次也是構建UIPageViewControllerDataSource中的兩個方法(ZPDFPageModel)。要注意他們返回的是UIViewController,具體實現請參考源碼。動畫
效果展現
源碼下載
PDFDemourl