Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

iphone - App Crashing when using large images on iOS 4.0

I've been having a problem to show large images on a scrollview, the images are 2,4 - 4,7 MB. It runs fine on the 3GS and on the simulator. But whenever I try to run on a 3G or iPod Touch 2G, it crashes.

I searched across the web and found the "imageNamed is evil" article. Ok I changed all my image calls to imageWithContentsOfFile: but it still crashes, the only different that I see is that now images are deallocated after I leave the view just fine. But the memory usage is still very high.

Here is a screenshot of Instruments. alt text First peak is a video I show at startup, then the tableview shows a lot of images, until then no problems.

alt text When I enter a 1,1mb - 2576 x 1000 picture

alt text When I enter a 4,8mb - 7822 x 1000 picture

By the way the app was tested on iOS 4 and 3.1.2

Do you have any tips? Because this problem is driving me nuts.

Since now thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recently ran into the same problem while testing an app on my 3G. I ended up scaling down any images larger than a maximum number of pixels (I found that 2 million pixels seemed to work reliably on my 3G, but hotpaw2's answer seems to suggest that 1 million pixels may be a safer bet).

UIImage *image = // ...;
if (image.size.width * image.size.height > MAX_PIXELS) {
    // calculate the scaling factor that will reduce the image size to MAX_PIXELS
    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float scale = sqrt(image.size.width * image.size.height / MAX_PIXELS);

    // resize the image
    CGRect rect = CGRectMake(0.0, 0.0, floorf(actualWidth / scale), floorf(actualHeight / scale));
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *imageToDraw = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // imageToDraw is a scaled version of image that preserves the aspect ratio
}

Apple also provides an example of developing a photo gallery app that uses CATiledLayer to tile very large images. Their example uses images that have been sliced into tiles of the appropriate sizes in advance. It is possible to slice the images into tiles on the fly in your iOS app, but doing so is quite slow on the device. Check out session 104 of this year's WWDC for the PhotoScroller example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...