从ios sdk中的文档目录加载图像
问题描述:
我实现了集合视图,在该视图上显示文档目录中的图像。从ios sdk中的文档目录加载图像
但是由于来自文档的图像加载,集合视图不能平滑滚动。
如果图像从主包加载,那么它工作正常。
我的代码如下:
UIImageView *img=[[UIImageView alloc]init];
img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];
img.contentMode=UIViewContentModeScaleAspectFit;
cell.backgroundView=img;
我应该使用线程?如果是的话,我该怎么做? 我该如何解决这个问题?
答
不需要使用线程。偶尔加载图像很好,问题在于你不断加载图像。
从主包加载可能工作正常,因为NSBundle缓存为您的图像。你可以使用NSCache来做同样的事情。
因此,不是这样的:
img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];
做这样的事情:
static NSCache *cache = nil;
if (!cache) {
cache = [[NSCache alloc] init];
[cache setCountLimit:10]; // check how much RAM your app is using and tweak this as necessary. Too high uses too much RAM, too low will hurt scrolling performance.
}
NSString *path = [[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"];
if ([cache objectForKey:path]) {
img.image=[cache objectForKey:path];
} else {
img.image=[UIImage imageWithContentsOfFile:path];
[cache setObject:img.image forKey:path];
}
如果最终你发现你需要使用线程,然后我会用一个GCD线程加载图像,但是然后将该图像插入到我在此示例代码中创建的相同NSCache对象中。基本上使用后台线程来尝试和预测哪些图像需要预加载,但允许NSCache决定在破坏它们之前将这些图像保存在RAM中的时间。
答
假设捆绑中的图像比文档文件夹中的图像小,否则没有区别。
是的,你应该使用线程。使用GCD是一个不错的选择,最重要的是不要直接使用单元格(你不知道它是否会在图像加载时被重用),而是使用内部的indexPath
阻止获取该单元格,如果不是nil
,则更新该图像。
'imageWithContentsOfFile:'不做任何缓存。 – Wain
哇!多么伟大的编码!!!!!非常感谢您的帮助.....再次感谢! – user2526811
但我怎么能做到这一点视频也?? **我的代码视频**'NSURL * fileURL = [NSURL fileURLWithPath:[[arr_videos objectAtIndex:indexPath.row] valueForKey:@“Video_path”]]; MPMoviePlayerController * mvplayer = [[MPMoviePlayerController alloc] initWithContentURL:fileURL]; cell.backgroundView = [[UIImageView alloc] initWithImage:[mvplayer thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame]];' – user2526811