通过使用低分辨率图像然后交换高分辨率图像来加速UIImagePickerController

时间:2012-10-03 13:03:07

标签: iphone objective-c ios cocoa-touch ipad

有关于image loading from the camera picker的精彩维基。这让我意识到以全分辨率拍摄图像的成本。

此刻,当拍摄照片时,我推动一个新的视图控制器并以全分辨率显示图像。推动视图是一个非常缓慢和波涛汹涌的体验(约1 fps!),我想要平滑。与在Instagram上挑选照片相比,我注意到他们使用低分辨率图像,然后交换完整图像。 (我需要完整的res图像,因为用户应该能够缩放和平移)

我想要的想法是这样的:

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingMediaWithInfo:(NSDictionary *)info 
{

    UIImage* fullImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    // Push a view controller and give it the image.....
}

- (void) viewDidLoad {

    CGSize smallerImageSize = _imageView.bounds;
    UIImage* smallerImage = [MyHelper quickAndDirtyImageResize:_fullImage     
                                                        toSize:smallerImageSize];

    // Set the low res image for now... then later swap in the high res
    _imageView.image = smallerImage;

    // Swap in high res image async
    // This is the part im unsure about... Im sure UIKit isn't thread-safe!
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, NULL), ^{
        _imageView.image = _fullImage;
    });
}

我认为UIImage在使用之前不会进行内存映射。因此,在给予imageView之前,它不会减慢速度。这是对的吗?

我认为图像解码已经由系统异步完成,但是,在加载时,它会大大减慢手机速度。

有没有办法执行在极低优先级后台队列中显示图像所需的一些工作?

3 个答案:

答案 0 :(得分:5)

你正在尝试以最复杂的方式做事:) 为什么不在推动视图控制器并将其传递给它们之前准备好小图像?看看这段代码:

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingMediaWithInfo:(NSDictionary *)info 
{

    UIImage *fullImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *smallImage = [fullImage imageScaledToSize:self.view.bounds];

    // Push a view controller and give it BOTH images
}

// And in your pushed view controller

- (void)viewDidLoad
{
    _imageView.image = self.smallImage;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    _imageView.image = self.fullImage;
}

最重要的是,动画完成后会立即调用viewDidAppear:,这样您就可以毫无顾虑地在此处切换图像。

答案 1 :(得分:3)

除了安德烈的回答之外,请使用imageScaledToSize,而不是使用CGImageSourceCreateThumbnailAtIndex。事实上,很可能(我很确定是这种情况)相册中使用的任何图像都有缩略图。因此,不要打扰图像本身,抓住现有的缩略图并显示它,然后使用Andrey的代码切换主图像。通过这种方式,您可以在动画期间尽可能少地完成工作。

调用CGImageSourceCreateThumbnailAtIndex将返回缩略图,无论它已经存在还是需要生成。因此使用起来非常安全,可能至少与imageScaledToSize一样快。

您可以在Apple文档中找到完整的代码示例,无需在此处复制。

答案 2 :(得分:1)

您是否尝试过使用ALAssetsLibrary加载该图片的缩略图,而不是尝试以全分辨率加载图片?它也比调整它的速度快。