gpt4 book ai didi

iphone - 异步文档中的图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:09:20 25 4
gpt4 key购买 nike

我需要从 NSDocumentDirectory 异步读取图像到多个 uiimageview,这样它就不会阻塞 UI。我知道我可以在后台使用执行选择器来加载 uiimage,但是我如何才能将它与动态 uiimageview 相关联?

最佳答案

一种方便的方法是使用 block ,例如:

[self loadFullImageAt:imagePath completion:^(UIIMage * image){
self.imageView.image = image;
}];

将图像作为数据加载的位置(因为 UIImage 否则会延迟加载图像数据 - 当您首次访问它时)。在后台线程中解压缩图像也是一个好主意,这样当我们第一次使用图像时主线程就不必这样做。

- (void)loadFullImageAt:(NSString *)imageFilePath completion:(MBLoaderCompletion)completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
UIImage *image = nil;
if (imageData) {
image = [[[UIImage alloc] initWithData:imageData] decodedImage];
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(image);
});
});
}

回调定义为:

typedef void (^MBLoaderCompletion)(UIImage *image);

下面是一个实现解压代码的UIImage类:

UIIMage+Decode.h

#import <UIKit/UIKit.h>


@interface UIImage (Decode)

- (UIImage *)decodedImage;

@end

UIIMage+Decode.m

#import "UIImage+Decode.h"


@implementation UIImage (Decode)

- (UIImage *)decodedImage {
CGImageRef imageRef = self.CGImage;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
CGImageGetWidth(imageRef),
CGImageGetHeight(imageRef),
8,
// Just always return width * 4 will be enough
CGImageGetWidth(imageRef) * 4,
// System only supports RGB, set explicitly
colorSpace,
// Makes system don't need to do extra conversion when displayed.
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
CGColorSpaceRelease(colorSpace);
if (!context) return nil;

CGRect rect = (CGRect){CGPointZero,{CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)}};
CGContextDrawImage(context, rect, imageRef);
CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);

UIImage *decompressedImage = [[UIImage alloc] initWithCGImage:decompressedImageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(decompressedImageRef);
return decompressedImage;
}

@end

此处提供的示例代码假设我们使用的是 ARC

关于iphone - 异步文档中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096338/

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