【问题标题】:iPhone Development - UIImageView memory issueiPhone 开发 - UIImageView 内存问题
【发布时间】:2011-01-16 03:55:59
【问题描述】:

背景:

受 Apple 的示例代码 ScrollViewSuite 的启发,我创建了一个显示图片缩略图和一张选定图片的视图控制器类。 “选定”图片的控件层次结构如下所示:

--> UIView
    --> UIScrollView
        --> UIImageView

以下代码用于将 UIScrollView 放到视图上:

imageScrollView = [[UIScrollView alloc] initWithFrame:frame];
[imageScrollView setBackgroundColor:[UIColor clearColor]];
[imageScrollView setDelegate:self];
[imageScrollView setBouncesZoom:YES];
[[self view] addSubview:imageScrollView];

...下面的代码用于配置UIImageView并将其添加到UIScrollView:

// Custom method to return a UIImage from a URL string
UIImage *image = [UIImage newImageWithContentsOfURL:imageURL];  

// first remove previous image view, if any
[[imageScrollView viewWithTag:MAIN_IMAGE_TAG] removeFromSuperview];

// set the new image view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setDelegate:self];
[imageView setTag:MAIN_IMAGE_TAG];
[imageScrollView addSubview:imageView];
[imageScrollView setContentSize:[imageView frame].size];

// choose minimum scale so image width fits screen
float minScale  = [imageScrollView frame].size.width / [imageView frame].size.width;
[imageScrollView setMinimumZoomScale:minScale];
[imageScrollView setZoomScale:minScale];
[imageScrollView setContentOffset:CGPointZero];

// clear memory
[imageView release];
imageView = nil;

[image release];
image = nil;

这是我用来使用 URL 字符串获取 UIImage 的类别方法:

+ (UIImage *)newImageWithContentsOfURL:(NSString *)imageURL {   
    NSURL *url = [[NSURL alloc] initWithString:imageURL];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];
    [data release];
    [url release];

    return image;
}

问题: 加载大小为 110 Kb(大约)的 jpeg 图像的影响是应用程序的实际内存从 12 MB(大约)跃升至 38 MB(大约)。当我第一次看到这个时,我感到很困惑。这怎么可能?呃,最终结果:应用程序在 iPhone 3G 上崩溃(偶尔)。

请注意,内存读数是使用 Instruments 中的 Memory Monitor 工具获取的 - 在设备(而不是模拟器)上测试应用程序时。另请注意,Instruments 没有显示内存泄漏,Static Analyzer 也没有指出任何可疑之处。

我需要帮助!

【问题讨论】:

  • 将 1 x 110kb 图像加载到 imageView 后崩溃?
  • 是的。加载到 imageView 时 110 Kb 的图像使实际内存从 12 MB 拍摄到 38 MB。

标签: iphone memory uiscrollview uiimageview initwithcontentsofurl


【解决方案1】:

肯定它一定不是 jpeg 导致它使用这么多内存和崩溃的东西 - 我有一个 15200x250 像素的 png,它滚动得很漂亮......

【讨论】:

    【解决方案2】:

    这可能与压缩 jpeg 的事实有关。 它在显示时可能是未压缩的,因此内存中会出现巨大的跳跃。

    1:1 比例的图像尺寸是多少?

    【讨论】:

    • 原尺寸为2272 × 1704
    • 我猜你对压缩和解压缩的看法可能是对的。我怎样才能避免这种减压?
    • 这是在 iPhone 上使用的巨大图像。不能调整大小吗?这就是它占用这么多内存的原因,就像一张 3 兆像素的图像。
    • 这是我不知道的事情:文件大小不等于内存大小。对于图像,文件大小无关紧要。唯一真正重要的尺寸是高度和宽度。内存 = 宽度 * 高度 * 4(2272 x 1704 * 4 = 15,485,952 字节)。我所要做的就是在将图像放入 UIScrollView 之前缩小图像(并将其显示)。感谢您为我指明正确的方向。
    • 只是出于兴趣和好奇,您是从哪里发现这种计算图像内存大小的方法的?
    猜你喜欢
    • 2010-10-03
    • 2015-05-03
    • 2011-05-19
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多