我正在try 将UIImage加载到背景线程中,然后在iPad上显示它们.然而,当我将imageViews的view属性设置为图像时,会出现一个口吃.

CGImage/UIImage lazily loading on UI thread causes stutter

这实际上会强制将图像加载到线程中,但在显示图像时仍然会出现口吃.

你可以在这里找到我的示例项目:http://www.jasamer.com/files/SwapTest.zip(编辑:fixed version),判断SwapTestViewController.try 拖动图片以查看结巴.

我创建的测试代码是这样的(forceLoad方法取self 上面发布的堆栈溢出问题):

NSArray* imagePaths = [NSArray arrayWithObjects:
                       [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], 
                       [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil];

NSOperationQueue* queue = [[NSOperationQueue alloc] init];

[queue addOperationWithBlock: ^(void) {
    int imageIndex = 0;
    while (true) {
        UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]];
        imageIndex = (imageIndex+1)%2;
        [image forceLoad];

        //What's missing here?

        [self performSelectorOnMainThread: @selector(setImage:) withObject: image waitUntilDone: YES];
        [image release];
    }
}];

我知道口吃可以避免有两个原因:

(1) 苹果能够在照片应用程序中加载图像而不会出现口吃

(2) 在上述代码的修改版本中,占位符1和占位符2显示一次后,此代码不会导致口吃:

    UIImage* placeholder1 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil]];
[placeholder1 forceLoad];
UIImage* placeholder2 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil]];
[placeholder2 forceLoad];

NSArray* imagePaths = [NSArray arrayWithObjects:
                       [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], 
                       [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock: ^(void) {
    int imageIndex = 0;
    while (true) {
        //The image is not actually used here - just to prove that the background thread isn't causing the stutter
        UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]];
        imageIndex = (imageIndex+1)%2;
        [image forceLoad];

        if (self.imageView.image==placeholder1) {
            [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder2 waitUntilDone: YES];
        } else {
            [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder1 waitUntilDone: YES];
        }                

        [image release];
    }
}];

然而,我不能把所有的图片都留在记忆中.

这意味着forceLoad并不能完成全部工作——在实际显示图像之前,还有其他事情要做.

谢谢,朱利安

Update

使用了Tommys的一些技巧.我发现是CGSConvertBGRA888TorgBa8888花费了太多时间,所以看起来是 colored颜色 转换造成了延迟.

Running        Symbol Name
6609.0ms        CGSConvertBGRA8888toRGBA8888
6609.0ms         ripl_Mark
6609.0ms          ripl_BltImage
6609.0ms           RIPLayerBltImage
6609.0ms            ripc_RenderImage
6609.0ms             ripc_DrawImage
6609.0ms              CGContextDelegateDrawImage
6609.0ms               CGContextDrawImage
6609.0ms                CA::Render::create_image_by_rendering(CGImage*, CGColorSpace*, bool)
6609.0ms                 CA::Render::create_image(CGImage*, CGColorSpace*, bool)
6609.0ms                  CA::Render::copy_image(CGImage*, CGColorSpace*, bool)
6609.0ms                   CA::Render::prepare_image(CGImage*, CGColorSpace*, bool)
6609.0ms                    CALayerPrepareCommit_(CALayer*, CA::Transaction*)
6609.0ms                     CALayerPrepareCommit_(CALayer*, CA::Transaction*)
6609.0ms                      CALayerPrepareCommit_(CALayer*, CA::Transaction*)
6609.0ms                       CALayerPrepareCommit_(CALayer*, CA::Transaction*)
6609.0ms                        CALayerPrepareCommit
6609.0ms                         CA::Context::commit_transaction(CA::Transaction*)
6609.0ms                          CA::Transaction::commit()
6609.0ms                           CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)
6609.0ms                            __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
6609.0ms                             __CFRunLoopDoObservers
6609.0ms                              __CFRunLoopRun
6609.0ms                               CFRunLoopRunSpecific
6609.0ms                                CFRunLoopRunInMode
6609.0ms                                 GSEventRunModal
6609.0ms                                  GSEventRun
6609.0ms                                   -[UIApplication _run]
6609.0ms                                    UIApplicationMain
6609.0ms                                     main         

遗憾的是,他提出的最后一点面具改变并没有改变任何事情.

推荐答案

UIKit只能用于主螺纹.因此,您的代码在技术上是无效的,因为您使用的UIImage来自主线程以外的线程.您应该单独使用CoreGraphics在后台线程上加载(并非延迟解码)图形,将CGImageRef发布到主线程,并在那里将其转换为UIImage.在您当前的实现中,它似乎可以工作(尽管您不希望出现结巴),但它不能保证工作正常.这一地区似乎有很多迷信和不良行为,所以你设法找到一些不好的建议也就不足为奇了...

建议在后台线程上运行:

// get a data provider referencing the relevant file
CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename(filename);

// use the data provider to get a CGImage; release the data provider
CGImageRef image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, 
                                                    kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);

// make a bitmap context of a suitable size to draw to, forcing decode
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
unsigned char *imageBuffer = (unsigned char *)malloc(width*height*4);

CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef imageContext =
    CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace,
                  kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);

CGColorSpaceRelease(colourSpace);

// draw the image to the context, release it
CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
CGImageRelease(image);

// now get an image ref from the context
CGImageRef outputImage = CGBitmapContextCreateImage(imageContext);

// post that off to the main thread, where you might do something like
// [UIImage imageWithCGImage:outputImage]
[self performSelectorOnMainThread:@selector(haveThisImage:) 
         withObject:[NSValue valueWithPointer:outputImage] waitUntilDone:YES];

// clean up
CGImageRelease(outputImage);
CGContextRelease(imageContext);
free(imageBuffer);

如果您使用的是iOS 4或更高版本,则无需执行malloc/free,只需将NULL作为CGBitmapContextCreate的相关参数传递,并让CoreGraphics自行整理存储.

这与您发布到的解决方案不同,因为它:

  1. 从PNG数据源创建CGImage-延迟加载适用,因此这不一定是完全加载和解压缩的图像
  2. 创建与PNG大小相同的位图上下文
  3. 将PNG数据源中的CGImage绘制到位图上下文中——这将强制完全加载和解压缩,因为实际 colored颜色 值必须放在我们可以从C数组访问它们的地方.这一步就是你链接到的力载荷.
  4. 将位图上下文转换为图像
  5. 将该图像发布到主线程,可能会成为UIImage

因此,在加载的对象和显示的对象之间没有连续性;像素数据通过一个C数组(因此,没有隐藏骗局的机会),只有正确地将其放入数组中,才能生成最终图像.

Objective-c相关问答推荐

MKMapView 上的 UIPanGestureRecognizer?

Objective-C - 将浮点数转换为字符串的其他方法

Objective-c 点表示法或方括号表示法中首选什么?

如何从 C 方法调用 Objective-C 方法?

将 NSArray 保存到 NSUserDefaults 并在 NSMutableArray 中获取它

从 float 或 double 实例化 NSDecimalNumber 的正确方法

performSelector 的返回值:

go 掉 UISearchBar 下的 1px 边框

在 UILabel.attributedText *not* 蓝色和 *not* 下划线

如何构建一个 Objective-C 静态库?

如何正确获取文件大小并将其转换为 Cocoa 中的 MB、GB?

切换隐私设置将杀死应用程序

iOS7过度导航栏按钮填充

如何将日期字符串解析为 iOS 中的 NSDate 对象?

StoryBoard 助理编辑器停止显示相关文件

如何删除手势识别器

在 UICollectionView 上重置滚动

Objective-C 中的属性和实例变量

如何更新 Core Data 中的现有对象?

UIPageViewController,如何在不打乱数据源指定顺序的情况下正确跳转到特定页面?