【问题标题】:How to know when UIimageView finished loading?如何知道 UIimageView 何时完成加载?
【发布时间】:2011-07-05 05:08:14
【问题描述】:

在我的视图控制器中,我如何知道某个 UIImageView 何时完成加载(来自文档目录的大 jpeg)?我需要知道,以便我可以将占位符低分辨率图像视图与此高分辨率图像视图交换。我是否需要创建自定义回调才能知道这一点?任何方式都很好。

顺便说一下,这是我加载图像的sn-p代码:

NSString *fileName = [NSString stringWithFormat:@"hires_%i.jpg", currentPage];
NSString *filePath = [NSString stringWithFormat:@"%@/BookImage/%@", [self documentsDirectory], fileName];
hiResImageView.image = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];

【问题讨论】:

  • 请提供您的源代码如何加载图像。
  • 谢谢@Tim -- 这是其中的一些源代码。
  • “大型 jpeg”有多大?因为如果你说的非常大,你最好使用某种平铺。涉及 UIImageView 和大图像的性能影响很大。

标签: iphone objective-c uikit uiimageview


【解决方案1】:

UIImageView 根本没有进行任何加载。所有加载都由[[UIImage alloc] initWithContentsOfFile:filePath] 完成,并且在加载文件时您的线程被阻塞(因此在调用最终返回时加载已经完成)。

你想做的是这样的:

- (void)loadImage:(NSString *)filePath {
    [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:filePath];
}

- (void)loadImageInBackground:(NSString *)filePath {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    [self performSelectorOnMainThread:@selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES];
    [image release];
    [pool release];
}

- (void)didLoadImageInBackground:(UIImage *)image {
    self.imageView.image = image;
}

您可以设置self.imageView 来显示低分辨率图像,然后调用loadImage: 来加载高分辨率版本。

请注意,如果您在 didLoadImageInBackground: 被之前的调用调用之前重复调用此函数,您可能会导致设备内存不足。或者,您可能让第一次调用的图像比第二次调用的图像加载时间长得多,以至于didLoadImageInBackground: 在调用第一个图像之前先调用第二个图像。解决这些问题留给读者(或其他问题)作为练习。

【讨论】:

  • 谢谢,很好的答案。但是,是否 - (void)didLoadImageInBackground:(UIImage *)image 保证等到图像加载完成后?这是我关心的问题,运行时任务的实际排序..
  • 正如我之前所说,当[[UIImage alloc] initWithContentsOfFile:filePath] 返回时,图像已完成加载。
  • 不幸的是[[UIImage alloc] initWithContentsOfFile:filePath] 没有做所有的加载工作。它只是将文件加载到内存中。大部分过程是在绘制 UIImageView(解压缩/绘图/RGBA 转换)时完成的,不幸的是 iOS 没有任何委托或通知,例如 imageDidFinishedDrawing。您可以通过在imageWithContentsOfFile 之后放置NSLOG 来尝试此操作,您将看到在绘制图像之前执行了第一个 NSLOG。 (选择一个大的JPEG来测试它)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多