我想预加载图像,以便当我将它们的 UIImageView 添加到我的 currentView 时,PNG 已经在内存中、加载、膨胀等。
从这次分析可以看出,图像在显示时加载:
与此同时,我之前已经预加载了这些图像。就在我加载该 View 时,我使用该代码彻底创建了这些动画的所有图像和 ImageView :
- (UIImageView*)createAnimationForReel:(NSString*)reel ofType:(NSString*)type usingFrames:(NSInteger)frames{
UIImageView *imageView = [[UIImageView alloc] init];
NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:frames];
for (int i=0;i<frames;i++){
NSString *image;
if(i<10){
image = [NSString stringWithFormat:@"%@_0%i", reel, i];
} else {
image = [NSString stringWithFormat:@"%@_%i", reel, i];
}
NSString *path = [[NSBundle mainBundle] pathForResource:image ofType:@"png" inDirectory:type];
UIImage *anImage = [[UIImage alloc] initWithContentsOfFile:path];
[imageArray addObject:anImage];
}
imageView.animationImages = [NSArray arrayWithArray:imageArray];
imageView.animationDuration = 2.0;
return imageView;
}
当我阅读文档时它说:“此方法将图像数据加载到内存中并将其标记为可清除。如果数据被清除并需要重新加载,图像对象会从指定路径再次加载该数据。 “谈论 initWithContentOfFile。所以我的图像“应该”被加载。
但是没有。
我的反射(reflection)中肯定缺少某些东西。但是什么?
最佳答案
要强制完全预加载 UIImage,您需要实际绘制它,或者看起来是这样。例如使用:
- (void)preload:(UIImage *)image
{
CGImageRef ref = image.CGImage;
size_t width = CGImageGetWidth(ref);
size_t height = CGImageGetHeight(ref);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(space);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), ref);
CGContextRelease(context);
}
不漂亮,但它使绘制图像的速度提高了大约 4 倍。我在 iPhone 4S 上用 1 MB 640 × 1136 PNG 测试了这个:
- 在没有预加载的情况下绘制它大约需要 80 毫秒。
- 预加载图像标题大约需要 10 毫秒,但之后不会加快绘图速度。
- 通过数据提供程序预加载数据大约需要 100 毫秒,但之后几乎不会加快绘图速度。
- 如上面的代码所示,通过绘图进行预加载需要 100 毫秒,但下一次绘制只需 20 毫秒。
检查 https://gist.github.com/3923434用于测试代码。
关于ios - 强制加载 iOS 上的图像以预加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225609/