国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS實現PDF文件瀏覽功能

2020-07-26 02:20:17
字體:
來源:轉載
供稿:網友

寫了一個小Demo,顯示本地PDF格式文件,支持翻頁、跳頁、縮放。 

先看一下效果圖:

iOS開發,顯示PDF格式文件方法有很多:

  • 最簡單的應該是UIWebView,可以加載本地或網絡PDF文件,支持上下滑動瀏覽、縮放。
  • 優化一點的是用系統的QLPreviewController加載,實現起來也比較方便,支持上下滑動瀏覽,左后滑動可多PDF文件切換,同時支持原生的分享打印,QLPreviewController支持的文檔格式也比較多,如pdf、doc、docx、xls、xlsx、txt、ppt、mp4...
  • 上面兩種都沒有足夠的自定義空間,不在這里做過多的介紹了,另外一種也就是本篇用到的iOS核心圖形庫:Core Graphics,繪制PDF文檔。

簡單說一下邏輯,根據本地路徑獲取到CGPDFDocumentRef,在drawRect中繪制上下文,畫出PDF文件。通過UIScrollView實現縮放,添加UIGestureRecognizer實現單擊、雙擊、左滑、右滑功能。基于CATransition實現翻頁動畫。

下面貼上核心代碼:

承載PDF文件視圖的控制器:HWPDFBrowseVC

#import <UIKit/UIKit.h> @interface HWPDFBrowseVC : UIViewController @property (nonatomic, copy) NSString *filePath;@property (nonatomic, copy) NSString *fileName; @end /*** ---------------分割線--------------- ***/ #import "HWPDFBrowseVC.h"#import "HWPDFBrowseView.h"#import "HWPDFBrowseToolBar.h"#import "HWPDFBrowseScrollView.h" #define KPicMaxScale 3.0#define KMainW [UIScreen mainScreen].bounds.size.width#define KMainH [UIScreen mainScreen].bounds.size.height @interface HWPDFBrowseVC ()<UIScrollViewDelegate, HWPDFBroeseToolBarDelegate> @property (nonatomic, weak) HWPDFBrowseScrollView *scrollView;@property (nonatomic, weak) HWPDFBrowseView *browseView;@property (nonatomic, weak) HWPDFBrowseToolBar *toolBar;@property (nonatomic, assign) CGFloat minZoomScale;@property (nonatomic, assign) CGFloat lastScrContX; @end @implementation HWPDFBrowseVC - (void)viewDidLoad { [super viewDidLoad];  //初始化 self.view.backgroundColor = [UIColor whiteColor]; self.navigationItem.title = _fileName;  //創建控件 [self creatControl];} - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated];  //防止隱藏導航時,左滑返回導航消失 CGRect temNavBarFrame = self.navigationController.navigationBar.frame; temNavBarFrame.origin.y = 20; self.navigationController.navigationBar.frame = temNavBarFrame;} - (void)creatControl{ //導航右側按鈕 UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(9, 0, 40, 40)]; deleteBtn.titleLabel.font = [UIFont systemFontOfSize:16.f]; [deleteBtn setTitle:@"跳頁" forState:UIControlStateNormal]; [deleteBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [deleteBtn addTarget:self action:@selector(navBtnOnClick) forControlEvents:UIControlEventTouchUpInside]; UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; [rightView addSubview:deleteBtn]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];  //scrollView HWPDFBrowseScrollView *scrollView = [[HWPDFBrowseScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds]; scrollView.delegate = self; scrollView.backgroundColor = [UIColor blackColor]; scrollView.maximumZoomScale = KPicMaxScale; scrollView.showsVerticalScrollIndicator = NO; scrollView.showsHorizontalScrollIndicator = NO; [self.view addSubview:scrollView]; _scrollView = scrollView;  //pdf視圖 HWPDFBrowseView *browseView = [[HWPDFBrowseView alloc] initWithFilePath:_filePath]; [scrollView addSubview:browseView]; _browseView = browseView;  //繪制pdf視圖后縮放至屏幕完全居中顯示 CGRect frame = browseView.frame; frame.size.width = browseView.frame.size.width > KMainW ? KMainW : browseView.frame.size.width; frame.size.height = frame.size.width * (browseView.frame.size.height / browseView.frame.size.width); if (frame.size.height > KMainH) { frame.size.height = KMainH; frame.size.width = KMainH * (browseView.frame.size.width / browseView.frame.size.height); }  //根據縮放調整 _minZoomScale = frame.size.width / browseView.frame.size.width; scrollView.allowScrollScale = _minZoomScale; scrollView.minimumZoomScale = _minZoomScale; scrollView.zoomScale = _minZoomScale;  //底部工具欄 HWPDFBrowseToolBar *toolBar = [[HWPDFBrowseToolBar alloc] initWithFrame:CGRectMake(0, KMainH - 49, KMainW, 49) currentPage:_browseView.currentPage totalPage:_browseView.totalPages]; toolBar.delegate = self; [self.view addSubview:toolBar]; _toolBar = toolBar;  //單擊 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)]; tap.numberOfTouchesRequired = 1; tap.numberOfTapsRequired = 1; [scrollView addGestureRecognizer:tap];  //雙擊 UITapGestureRecognizer *tapDouble = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleClick)]; tapDouble.numberOfTapsRequired = 2; [scrollView addGestureRecognizer:tapDouble]; [tap requireGestureRecognizerToFail:tapDouble];  //右滑手勢 UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nextPage)]; rightSwip.direction = UISwipeGestureRecognizerDirectionLeft; [scrollView addGestureRecognizer:rightSwip];  //左滑手勢 UISwipeGestureRecognizer *leftSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(forwardPage)]; leftSwip.direction = UISwipeGestureRecognizerDirectionRight; [scrollView addGestureRecognizer:leftSwip];} - (void)navBtnOnClick{ [_toolBar showWindow];} //單擊屏幕顯示隱藏菜單- (void)click{ CGFloat navBarY = _toolBar.frame.origin.y == KMainH - 49 ? -64 : 20; CGFloat toolBarY = _toolBar.frame.origin.y == KMainH - 49 ? KMainH : KMainH - 49;  [UIView animateWithDuration:0.25 animations:^{ CGRect temNavBarFrame = self.navigationController.navigationBar.frame; temNavBarFrame.origin.y = navBarY; self.navigationController.navigationBar.frame = temNavBarFrame; CGRect temToolBarFrame = _toolBar.frame; temToolBarFrame.origin.y = toolBarY; _toolBar.frame = temToolBarFrame; }];} //雙擊屏幕放大縮小圖片- (void)doubleClick{ [UIView animateWithDuration:0.25f animations:^{ _scrollView.zoomScale = _scrollView.zoomScale == _minZoomScale ? KPicMaxScale : _minZoomScale; }];} //左滑事件- (void)nextPage{ [_browseView nextPage]; _toolBar.currentPage = _browseView.currentPage;} //右滑事件- (void)forwardPage{ [_browseView prePage]; _toolBar.currentPage = _browseView.currentPage;} #pragma mark - UICouseBrowseToolBarDelegate- (void)browseToolBar:(HWPDFBrowseToolBar *)browseToolBar didClickFinishButtonWithPage:(NSString *)page{ _browseView.currentPage = [page integerValue]; [_browseView reloadView]; [_toolBar dismissKeyboard]; _scrollView.zoomScale = _minZoomScale;} - (void)browseToolBar:(HWPDFBrowseToolBar *)browseToolBar didPageButtonWithAction:(BOOL)nextPage{ if (nextPage) { [self nextPage]; }else { [self forwardPage]; } _scrollView.zoomScale = _minZoomScale;} #pragma mark - UIScrollViewDelegate- (void)scrollViewDidZoom:(UIScrollView *)scrollView{ CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0; CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0; _browseView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY - 64);} - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{ return _browseView;} - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ if (scrollView.isZooming) return;  //允許翻頁的偏移量 CGFloat movePadding = 70.f;  //仿蘋果原生相冊,圖片放大后,滑動前在邊界時在可以翻頁,這里加了±10的偏移量 if (scrollView.contentOffset.x < - movePadding && _lastScrContX < 10) { _scrollView.zoomScale = _minZoomScale; [self forwardPage]; }  if (scrollView.contentSize.width - scrollView.contentOffset.x < KMainW - movePadding && scrollView.contentSize.width != 0 && fabsf(_lastScrContX + KMainW - scrollView.contentSize.width) < 10) { _scrollView.zoomScale = _minZoomScale; [self nextPage]; }} //滑動自然停止時調用- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ _lastScrContX = scrollView.contentOffset.x;} //滑動手動停止時調用- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ _lastScrContX = scrollView.contentOffset.x;} - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.} @end

PDF文件視圖:HWPDFBrowseView

#import <UIKit/UIKit.h> @interface HWPDFBrowseView : UIView{ CGPDFDocumentRef pdfDocumentRef;} @property (nonatomic, assign) NSInteger currentPage;@property (nonatomic, assign) NSInteger totalPages; - (id)initWithFilePath:(NSString *)filePath;- (void)reloadView;- (void)prePage;- (void)nextPage; @end /*** ---------------分割線--------------- ***/ #import "HWPDFBrowseView.h" @implementation HWPDFBrowseView - (id)initWithFilePath:(NSString *)filePath{ pdfDocumentRef = [self createPDFFromExistFile:filePath];  self = [super initWithFrame:CGPDFPageGetBoxRect(CGPDFDocumentGetPage(pdfDocumentRef, 1), kCGPDFMediaBox)];  return self;} - (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath{ CFStringRef path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8); CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO); CFRelease(path); CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(urlRef); CFRelease(urlRef); _totalPages = CGPDFDocumentGetNumberOfPages(document); _currentPage = 1; if (_totalPages == 0) return NULL;  return document;} - (void)reloadView{ [self setNeedsDisplay];} - (void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor whiteColor] set]; CGContextFillRect(context, rect); CGContextTranslateCTM(context, 0.0, rect.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocumentRef, _currentPage); CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, rect, 0, true); CGContextConcatCTM(context, pdfTransform); CGContextDrawPDFPage(context, page);} //上一頁- (void)prePage{ if(_currentPage < 2) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已經第一頁了!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil ]; [alert show]; return; }  --_currentPage; [self reloadView]; [self transitionWithType:@"pageUnCurl" WithSubtype:kCATransitionFromRight ForView:self];} //下一頁- (void)nextPage{ if(_currentPage >= _totalPages) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已經最后一頁了!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil ]; [alert show]; return; }  ++_currentPage; [self reloadView]; [self transitionWithType:@"pageCurl" WithSubtype:kCATransitionFromRight ForView:self];} //設置翻頁動畫效果- (void)transitionWithType:(NSString *)type WithSubtype:(NSString *)subtype ForView:(UIView *)view{ CATransition *animation = [CATransition animation]; animation.duration = 0.7f; animation.type = type; if (subtype) animation.subtype = subtype; animation.timingFunction = UIViewAnimationOptionCurveEaseInOut; [view.layer addAnimation:animation forKey:@"animation"];} @end

Demo 下載鏈接

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洪江市| 威海市| 察雅县| 北川| 桃江县| 桂林市| 唐山市| 博罗县| 称多县| 科尔| 延庆县| 元阳县| 彭阳县| 堆龙德庆县| 墨玉县| 泰宁县| 虹口区| 吴忠市| 聊城市| 玉田县| 额济纳旗| 聂荣县| 兴隆县| 玛多县| 宽甸| 江川县| 九龙城区| 六盘水市| 家居| 庄河市| 鹤峰县| 禹城市| 伊宁市| 吴川市| 社旗县| 方正县| 松滋市| 得荣县| 福泉市| 富蕴县| 汝南县|