在开发过程中,经常会读取本地图片。本人在开发过程中,发现读取图片会存在延迟,这个延迟就会导致页面卡顿。
参考YYImage。
.h文件代码
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (RJFastRead)
/**
快速读取图片
@param name 图片名字
@return 目标对象
*/
+ (nullable UIImage *)fast_imageNamed:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
.m文件代码
#import "UIImage+RJFastRead.h"
/* 主要代码来自 YYImage,对其做了部分逻辑修改和拓展 */
// 获取当前设备最佳读取分辨率顺序
static NSArray *_NSBundlePreferredScales() {
static NSArray *scales;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale <= 1) {
scales = @[@1,@2,@3];
} else if (screenScale <= 2) {
scales = @[@2,@3,@1];
} else {
scales = @[@3,@2,@1];
}
});
return scales;
}
// 拼接图片名称和分辨率后缀(考虑到单双精度一贯的不稳定性,去除了源码对 float 类型的转换使用,保证安全)
static NSString *_NSStringByAppendingNameScale(NSString *string, NSNumber *scale) {
if (!string) return nil;
if ([scale isEqualToNumber:@1] || string.length == 0 || [string hasSuffix:@"/"]) return string.copy;
return [string stringByAppendingFormat:@"@%@x", scale];
}
@implementation UIImage (RJFastRead)
+ (UIImage *)fast_imageNamed:(NSString *)name {
if (name.length == 0) return nil;
if ([name hasSuffix:@"/"]) return nil;
NSString *res = name.stringByDeletingPathExtension;
NSString *ext = name.pathExtension;
NSString *path = nil;
NSNumber *scale = @1;
// If no extension, guess by system supported (same as UIImage).
NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp", @"apng"];
NSArray *scales = _NSBundlePreferredScales();
for (int s = 0; s < scales.count; s++) {
scale = scales[s];
NSString *scaledName = _NSStringByAppendingNameScale(res, scale);
for (NSString *e in exts) {
path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e];
if (path) break;
}
if (path) break;
}
// Support Assets.xcassets.
if (path.length == 0) {
return [self imageNamed:name];
}
return [UIImage imageWithContentsOfFile:path];
}
@end