美文网首页AppleDeveloper
iOS为本地文件生成预览图

iOS为本地文件生成预览图

作者: _我和你一样 | 来源:发表于2022-08-31 14:15 被阅读0次

几乎在所有的文件系统中,预览图或者缩略图都是很常见的,可以帮用户快速识别文件内容。

在iOS系统的文件app,也能看到各种常见文件的预览图,比如图片类、视频类、文档类、文本类 等。

当我们的应用需要展示本地预览图时改如何实现呢?

通过查阅Apple开发文档可知,在iOS13+,Apple为我们提供了实用QuickLook框架生成缩略图的功能,阅读开发文档不难实现这个功能。

这里使用OC代码演示:

首先需要导入头文件

#import <QuickLookThumbnailing/QuickLookThumbnailing.h>

然后根据本地路径,要生成的尺寸,创建生成缩略图请求

QLThumbnailGenerationRequest *request =  [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:fileURL size:size scale:UIScreen.mainScreen.scale representationTypes:QLThumbnailGenerationRequestRepresentationTypeThumbnail];

使用缩略图生成器单例对象,生成缩略图

[QLThumbnailGenerator.sharedGenerator generateRepresentationsForRequest:request updateHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, QLThumbnailRepresentationType type, NSError * _Nullable error) {
              // thumbnail.UIImage
 }];

其中需要注意的是:类型

请求时的类型:QLThumbnailGenerationRequestRepresentationTypes

QLThumbnailGenerationRequestRepresentationTypeAll 所有类型
QLThumbnailGenerationRequestRepresentationTypeIcon = 1 << 0 文件类型icon
QLThumbnailGenerationRequestRepresentationTypeLowQualityThumbnail = 1 << 1 低质量缩略图
QLThumbnailGenerationRequestRepresentationTypeThumbnail = 1 << 2 缩略图

结果中可以缩略图类型,以及对应的UIImage,NSImage,CGImage ,可以根据需要使用。

如果系统不支持图片返回nil,如果出错可以检查错误。

相关文章

网友评论

    本文标题:iOS为本地文件生成预览图

    本文链接:https://www.haomeiwen.com/subject/gdsdnrtx.html