iOS13 (三)截屏-PDF长图

2,780 阅读2分钟

在iOS13中,苹果提供了截屏选择PDF长图的功能,实现相关代码后,只需要使用截屏功能,就会发现在右边有一个"整页"的选项,可以编辑并保存长图。我封装了一个工具类,使用的时候只要写一句代码就可以啦。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长图的关键 如果不这样设置,截图只有屏幕显示的区域会有图案其他区域是空白,或其他问题

    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长图、双三指手势

如发现遗漏或者错误,请在下方评论区留言。