在iOS13中,蘋果提供了截屏選擇PDF長圖的功能,實現相關代碼后,只需要使用截屏功能,就會發(fā)現在右邊有一個"整頁"的選項,可以編輯并保存長圖。我封裝了一個工具類,使用的時候只要寫一句代碼就可以啦。swift版本的暫時還沒整理。

// 注冊截屏長圖功能?(一句代碼?? 支持scrollView、tableView、collectionView)
[[LXJScreenShotManager shareInstance] configScreenShot:self.scrollView];
下面就是工具類中的具體代碼
.h文件
#import <Foundation/Foundation.h>
/// 截屏PDF長圖
@interface LXJScreenShotManager : NSObject
/// 單例
+ (instancetype)shareInstance;
/// 初始化??scrollView:支持scrollView、tableView、collectionView
- (void)configScreenShot:(UIScrollView *)scrollView;
@end
.m文件
#import "LXJScreenShotManager.h"
static LXJScreenShotManager *screenShotInstance = nil;
@interface LXJScreenShotManager ()<UIScreenshotServiceDelegate>
@property (nonatomic, strong) UIScrollView *contentScrollView;//內容view
@end
@implementation LXJScreenShotManager
/// 單例
+ (instancetype)shareInstance {
????static dispatch_once_t once;
????dispatch_once(&once, ^{
????????screenShotInstance = [LXJScreenShotManager new];
????});
????return screenShotInstance;
}
/// 初始化??scrollView:支持scrollView、tableView、collectionView
- (void)configScreenShot:(UIScrollView *)scrollView {
????self.contentScrollView = scrollView;
????// iOS13及以上版本
????if (@available(iOS 13.0, *)) {
????????// 只要加了這個代理,截屏的時候就會有"整頁"的選項
????????UIApplication.sharedApplication.keyWindow.windowScene.screenshotService.delegate = self;
????}else{
????}
}
// MARK: - UIScreenshotServiceDelegate
- (void)screenshotService:(UIScreenshotService *)screenshotService generatePDFRepresentationWithCompletion:(void (^)(NSData * _Nullable, NSInteger, CGRect))completionHandler{
????completionHandler([self getScreenShotData],0,CGRectZero);
}
// MARK: - 生成PDF長圖 (scrollView → PDFdata)
- (NSData *)getScreenShotData{
????CGRect savedFrame = self.contentScrollView.frame;// 記錄原frame
????CGPoint savedContentOffset = self.contentScrollView.contentOffset;//屏幕上移的高度
????// 這一句是生成PDF長圖的關鍵 如果不這樣設置,截圖只有屏幕顯示的區(qū)域會有圖案其他區(qū)域是空白,或其他問題
????self.contentScrollView.frame = CGRectMake(0, 0, self.contentScrollView.contentSize.width, self.contentScrollView.contentSize.height);
????// 生成的PDF圖片存儲在pdfData
????NSMutableData *pdfData = [NSMutableData data];
????UIGraphicsBeginPDFContextToData(pdfData, self.contentScrollView.frame, NULL);
????UIGraphicsBeginPDFPage();// 開始
????[self.contentScrollView.layer renderInContext:UIGraphicsGetCurrentContext()];// 渲染 上下文
????UIGraphicsEndPDFContext();// 結束
????self.contentScrollView.frame = savedFrame;// 恢復frame
????self.contentScrollView.contentOffset = savedContentOffset;// 如果不設置這一句,屏幕可能會移動
????return pdfData;
}
@end
注意:如果是?tableView?的話會導致所有?cell?都被加載出來,如果當前控制器是一個無限列表,請不要使用這個功能。
Demo:《截屏PDF長圖、雙三指手勢》
如發(fā)現遺漏或者錯誤,請在下方評論區(qū)留言。