2

我正在开发一个带有画廊的应用程序。所有图像都在设备光盘(文档目录)上,但我无法顺利显示。

由于某些图像很大(2000px * 2000px),我将它们加载到后台线程中,缩小它们然后在主线程上显示它们。

这是我的 UIImageView 扩展:

@implementation UIImageView (BackgroundResize) 

- (void)localImageFromPath: (NSString *) path scaledTo: (CGSize) size {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_async(queue, ^{
        //Load image
        NSData * imgData = [[NSData alloc] initWithContentsOfFile:path];
        UIImage * original = [[[UIImage alloc]  initWithData:imgData] autorelease];
        [imgData release];
        CGSize imgSize = original.size;
        float widthScale = size.width / imgSize.width;
        float heightScale = size.height / imgSize.height;
        float scaleFactor = widthScale;
        if (heightScale < scaleFactor) {
            scaleFactor = heightScale;
        }
        UIImage * result = nil;
        //Scale if necessary
        if (scaleFactor < 1.0) {
            result = [[UIImage alloc] initWithCGImage:original.CGImage scale:1/scaleFactor orientation:original.imageOrientation];
        } else {
            result = [original retain];
        }
        NSLog(@"Image prepeared on backgroud thread, update ui image on main..");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Begin updating image on main thread");
            self.image = result;
            [result release];
            [[NSNotificationCenter defaultCenter] postNotificationName:NTF_IMG_LOADED object:self];
            NSLog(@"Updated");
        });

    });
    dispatch_release(queue);

}
@end

在控制台输出中,一切似乎都很完美,所有调试字符串都在不到 1 秒的时间内显示(对于 6 个非常大的图像),但 UI 被阻止并且图像显示延迟 10 秒。

在 iOS 上显示大型本地图像的正确方法是什么?

应用程序是为 iOS5+ 构建的..

谢谢,

4

1 回答 1

2

您实际上并没有调整图像的大小。该scale参数-initWithCGImage:scale:设置图像像素与屏幕坐标点的比例;它对底层图像没有任何作用。您需要将图像实际绘制到 aCGContext以缩小它:

    //Load image
    UIImage * original = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];

    CGSize imgSize = original.size;
    float widthScale = size.width / imgSize.width;
    float heightScale = size.height / imgSize.height;
    float scaleFactor = widthScale;
    if (heightScale < scaleFactor) {
        scaleFactor = heightScale;
    }

    UIImage * result = nil;
    //Scale if necessary
    if (scaleFactor < 1.0) {
        CGSize newSize = CGSizeMake(floorf(imgSize.width * scaleFactor),
                                    floorf(imgSize.height * scaleFactor));
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
        [original drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        result = UIGraphicsGetImageFromCurrentImageContext();
        [result retain];
        UIGraphicsEndImageContext();
    } else {
        result = [original retain];
    }
于 2013-04-06T17:50:09.803 回答