幾乎在所有的文件系統(tǒng)中,預(yù)覽圖或者縮略圖都是很常見的,可以幫用戶快速識別文件內(nèi)容。
在iOS系統(tǒng)的文件app,也能看到各種常見文件的預(yù)覽圖,比如圖片類、視頻類、文檔類、文本類 等。
當(dāng)我們的應(yīng)用需要展示本地預(yù)覽圖時改如何實現(xiàn)呢?
通過查閱Apple開發(fā)文檔可知,在iOS13+,Apple為我們提供了實用QuickLook框架生成縮略圖的功能,閱讀開發(fā)文檔不難實現(xiàn)這個功能。
這里使用OC代碼演示:
首先需要導(dǎo)入頭文件
#import <QuickLookThumbnailing/QuickLookThumbnailing.h>
然后根據(jù)本地路徑,要生成的尺寸,創(chuàng)建生成縮略圖請求
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 低質(zhì)量縮略圖
QLThumbnailGenerationRequestRepresentationTypeThumbnail = 1 << 2 縮略圖
結(jié)果中可以縮略圖類型,以及對應(yīng)的UIImage,NSImage,CGImage ,可以根據(jù)需要使用。
如果系統(tǒng)不支持圖片返回nil,如果出錯可以檢查錯誤。
除了使用系統(tǒng)API來生成預(yù)覽圖,也可以直接通過SDWebImage來生成縮略圖
// 注意,API用的是像素,我們一般要乘以scale
CGSize thumbnailSize = CGSizeMake(24 * UIScreen.mainScreen.scale, 24 * UIScreen.mainScreen.scale);
NSURL *fileURL = ...;
[self.iconImageView sd_setImageWithURL:fileURL placeholderImage:[UIImage imageNamed:model.fileImgStr] options:0 context:@{SDWebImageContextImageThumbnailPixelSize : @(thumbnailSize)}];
當(dāng)然支持的類型可能沒有系統(tǒng)的多,比如無法對文本文件、PDF等文件生成預(yù)覽圖。