在iOS13中,蘋果提供了截屏選擇PDF長圖的功能,實現相關代碼後,只須要使用截屏功能,就會發如今右邊有一個"整頁"的選項,能夠編輯並保存長圖。我封裝了一個工具類,使用的時候只要寫一句代碼就能夠啦。Swift版本的暫時還沒整理。工具
// 註冊截屏長圖功能 (一句代碼🤣)atom
[[LXJScreenShotManager shareInstance] configScreenShot:self.scrollView];spa
下面就是工具類中的具體代碼代理
.h文件cdn
#import <Foundation/Foundation.h>blog
/// 截屏PDF長圖圖片
@interface LXJScreenShotManager : NSObjectget
/// 單例it
+ (instancetype)shareInstance;io
/// 初始化 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長圖的關鍵 若是不這樣設置,截圖只有屏幕顯示的區域會有圖案其餘區域是空白,或其餘問題
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 都被加載出來,若是當前控制器是一個無限列表,請不要使用這個功能。
如發現遺漏或者錯誤,請在下方評論區留言。