我有一个 tableview,它运行一些代码在后台线程中从 NSData 获取 UIImage,然后在前台它调用 [button setImage:image forState:UIControlStateNormal];
。
问题是它会在该行卡住 UI 一瞬间,直到它完成。这意味着 UI 在将其设置为图像时会卡住。因为用户正在滚动,所以这是非常明显和紧张的。有什么方法可以避免我的 UI 像这样卡住吗?
dispatch_queue_t cellSetupQueue = dispatch_queue_create("Setup", NULL);
dispatch_async(cellSetupQueue, ^{
UIImage *image = [self.mediaDelegate largeThumbnailForMediaAtIndex:indexPath.row];
dispatch_async(dispatch_get_main_queue(), ^{
[self.thumbnailButton setImage:image forState:UIControlStateNormal];
});
});
dispatch_release(cellSetupQueue);
最佳答案
我猜你的图片是 JPG。如果是这样,那么 UIImage 将推迟对实际图像的解码,直到它第一次真正需要这些像素时。查看 ImageIO 框架以获得更精确的控制。这是我使用的一个片段:
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); // data is your image file NSData
if (source)
{
NSDictionary *dict = @{ (__bridge NSString *)kCGImageSourceShouldCache : @(YES) };
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)dict);
if (cgImage)
{
CFRelease(source);
return cgImage; // you can keep this reference so you dont have to decode again later
}
}
重要的部分是kCGImageSourceShouldCache
选项。您可以在后台线程上运行此代码并将解码后的图像传递给 UI 线程。
关于objective-c - 设置图像 : forState: lagging the UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041041/