gpt4 book ai didi

iphone - UIImage解压导致滚动滞后

转载 作者:IT王子 更新时间:2023-10-29 07:49:52 25 4
gpt4 key购买 nike

我有一个带有全屏 tableView 的应用程序,它显示了一堆小图像。这些图像是从网络上提取的,在后台线程上处理,然后使用类似以下内容保存到磁盘:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
// code that adds some glosses, shadows, etc
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();

NSData* cacheData = UIImagePNGRepresentation(output);
[cacheData writeToFile:thumbPath atomically:YES];

dispatch_async(dispatch_get_main_queue(), ^{
self.image = output; // refreshes the cell using KVO
});
});

此代码仅在第一次显示单元格时执行(因为此后图像已在磁盘上)。在这种情况下,使用以下方法加载单元格:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *savedImage = [UIImage imageWithContentsOfFile:thumbPath];

if(savedImage) {
dispatch_async(dispatch_get_main_queue(), ^{
self.image = savedImage; // refreshes the cell using KVO
});
}
});

我的问题是,在第一种情况下,滚动非常流畅。但在第二种情况下(它直接从磁盘读取图像),滚动非常不稳定,即使图像已加载。绘图是导致延迟的原因。使用 Instruments,我看到 copyImageBlockSetPNGpng_read_nowinflate 占用了大部分 cpu(它们在分配 self.图片UIGraphicsGetImageFromCurrentImageContext())

我假设发生这种情况是因为在第一种情况下 UIImage 是绘图的原始输出,而在第二种情况下它必须在每次绘制时解压缩 PNG。我尝试使用 JPG 而不是 PNG,我得到了类似的结果。

有办法解决这个问题吗?也许让它只在第一次绘制时解压缩 PNG?

最佳答案

你的问题是 +imageWithContentsOfFile: 被缓存和延迟加载。如果您想做这样的事情,请在您的后台队列中使用此代码:

// Assuming ARC
NSData* imageFileData = [[NSData alloc] initWithContentsOfFile:thumbPath];
UIImage* savedImage = [[UIImage alloc] initWithData:imageFileData];

// Dispatch back to main queue and set image...

现在,使用这段代码,图像数据的实际解压缩仍然是惰性的,并且会花费一点点,但不会像您在代码示例中通过延迟加载获得的文件访问命中率那么多。

由于您仍然看到性能问题,您还可以强制 UIImage 在后台线程上解压缩图像:

// Still on background, before dispatching to main
UIGraphicsBeginImageContext(CGSizeMake(100, 100)); // this isn't that important since you just want UIImage to decompress the image data before switching back to main thread
[savedImage drawAtPoint:CGPointZero];
UIGraphicsEndImageContext();

// dispatch back to main thread...

关于iphone - UIImage解压导致滚动滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10149165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com