我的应用程序是一种图片库。当用户点击图库中的图标时,需要显示图像(横向 2 图像,纵向 1 图像)。图片可能超过100。我通常将原始文件解码为UIImage格式。如果用户想要查看另一张图像,由于解码需要一些时间(延迟)来显示图像。所以我想在一个单独的线程(GCD)中将一些图像保存到缓存(NSArray)中来解决这个问题。
在数组中,我可以存储 5 到 10 张图像。每次用户滑动时都需要更新。
请提出建议。
提前致谢。
我的应用程序是一种图片库。当用户点击图库中的图标时,需要显示图像(横向 2 图像,纵向 1 图像)。图片可能超过100。我通常将原始文件解码为UIImage格式。如果用户想要查看另一张图像,由于解码需要一些时间(延迟)来显示图像。所以我想在一个单独的线程(GCD)中将一些图像保存到缓存(NSArray)中来解决这个问题。
在数组中,我可以存储 5 到 10 张图像。每次用户滑动时都需要更新。
请提出建议。
提前致谢。
我已经使用 GCD 实现了 NSCache
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self storeInCache];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image=[_imageCache objectForKey:@"P5"];
self.imageView = [[UIImageView alloc] initWithImage:image];
self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size};
[self.scrollView addSubview:self.imageView];
self.scrollView.contentSize = image.size;
});
});
// 将 5 张图片存入 NSCache
-(void)storeInCache
{
UIImage *image = [UIImage imageNamed:@"photo1.png"];
[_imageCache setObject:image forKey:@"P1"];
UIImage *image2 = [UIImage imageNamed:@"photo2.png"];
[_imageCache setObject:image2 forKey:@"P2"];
UIImage *image3 = [UIImage imageNamed:@"photo3.png"];
[_imageCache setObject:image3 forKey:@"P3"];
UIImage *image4 = [UIImage imageNamed:@"photo4.png"];
[_imageCache setObject:image4 forKey:@"P4"];
UIImage *image5 = [UIImage imageNamed:@"photo5.png"];
[_imageCache setObject:image5 forKey:@"P5"];
}
试试这个 -
UIImage *image = [imageCache objectForKey:@"myImage"];
if (!image)
{
// download image
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourURL]];
if (imageData)
{
// Set image to cache
[imageCache setObject: [UIImage imageWithData:imageData] forKey:@"myImage"];
dispatch_async(dispatch_get_main_queue(), ^{
[yourImageView setImage:[UIImage imageWithData:imageData]];
});
}
});
}
else
{
// Use image from cache
[yourImageView setImage:image];
}
您可以使用Apple 的LazyTableImages。
此代码将在后台下载图像并在下载完成时设置为 imageview。您可以添加占位符图像,直到您的原始图像处于下载过程中。
我在许多应用程序中都使用了此示例,因此如果您需要,我也可以帮助您实施。
希望这会帮助你。