简体   繁体   English

setImage:forState:滞后于UI

[英]setImage: forState: lagging the UI

I have a tableview which runs some code for fetching a UIImage from NSData in a background thread, then in the foreground it calls [button setImage:image forState:UIControlStateNormal]; 我有一个tableview,它运行一些代码以在后台线程中从NSData中获取UIImage,然后在前台调用[button setImage:image forState:UIControlStateNormal]; .

The problem is that it freezes the UI for a split second on that line, until it's complete. 问题是它将冻结用户界面的那一瞬间,直到完成为止。 This means that the UI freezes while it sets it as the image. 这意味着,UI在将其设置为图像时冻结。 Because the user is scrolling, this is very noticeable and jittery. 由于用户正在滚动,因此非常明显且令人不安。 Is there any way to avoid my UI from freezing like this? 有什么办法可以避免这样的用户界面冻结?

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);

I'm guessing your images are JPGs. 我猜您的图像是JPG。 If so then UIImage will defer decoding the actual image until the first time it actually needs those pixels. 如果是这样,则UIImage将延迟对实际图像进行解码,直到第一次真正需要这些像素为止。 Check out the ImageIO framework for more precise control on this. 查看ImageIO框架以对此进行更精确的控制。 Here's a snippet I use: 这是我使用的代码段:

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
    }
}

The important part is the kCGImageSourceShouldCache option. 重要的部分是kCGImageSourceShouldCache选项。 You can run this code on the background thread and pass the decoded image to the UI thread. 您可以在后台线程上运行此代码,并将解码的图像传递到UI线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM