为什么我的UIImage占用这么多内存?

我有一个UIImage,我正在加载到我的应用程序的意见之一。 这是一个10.7 MB的图像,但是当它在应用程序中加载时,应用程序的资源使用突然跳跃了50 MB。 为什么这样做? 不应该使用的内存仅增加10.7MB? 我确定加载映像是什么原因导致内存使用跳转,因为我尝试将这些行注释掉,内存使用量回到了8 MB左右。 以下是我如何加载图像:

UIImage *image = [UIImage imageNamed:@"background.jpg"]; self.backgroundImageView = [[UIImageView alloc] initWithImage:image]; [self.view addSubview:self.backgroundImageView]; 

如果没有办法减less这个图像使用的内存,是否有办法强制它释放,当我想要它? 我正在使用ARC。

正如@rckoenes所说,不要显示高文件大小的图像。 在显示图像之前,您需要调整图像大小。

 UIImage *image = [UIImage imageNamed:@"background.jpg"]; self.backgroundImageView =[self imageWithImage:display scaledToSize:CGSizeMake(20, 20)];//Give your CGSize of the UIImageView. [self.view addSubview:self.backgroundImageView]; -(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { //UIGraphicsBeginImageContext(newSize); // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution). // Pass 1.0 to force exact pixel size. UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } 

不,不应该是10.7MB。 10.7MB是图像的压缩大小。 加载到UIImage对象的图像是解码图像。

对于图像中的每个像素,使用4个字节(R,G,B和Alpha),因此可以计算内存大小,高度x宽度x 4 =内存中的总字节数。

所以,当你将图像加载到内存中时,它将占用大量的内存,并且由于使用UIImageView呈现图像,并将其作为子视图保存在内存中。

您应该尝试更改图像的大小以匹配iOS屏幕大小的大小。

你可以做一件事。 如果你能买得起这个图像50 MB的。 如果这个10 MB大小的图像对于你的应用来说非常重要。 你可以在使用它之后立即释放它来保持内存使用的控制。 正如你使用的ARC没有发布的选项,但你可以做到这一点

 @autoreleasepool { UIImage *image = [UIImage imageNamed:@"background.jpg"]; self.backgroundImageView = [[UIImageView alloc] initWithImage:image]; [self.view addSubview:self.backgroundImageView]; } 

使用autoreleasepool它将确保在此之后autoreleasepool {}块内存的胖图像将被释放。 使您的设备RAM再次开心。

希望能帮助到你 !