Scale image to fit screen on iPhone rotation

user467225 picture user467225 · Nov 18, 2010 · Viewed 9.6k times · Source

I have a UIScrollView containing an UIImageView and I have some trouble to get the correct behavior when the iPhone rotates.

Goal: I am trying to obtain the following when going from portrait to landscape:

_________
|AAAAAAA|
|BBBBBBB|         _________________
|CCCCCCC|         |     AAAAAA     |
|DDDDDDD|    -->  |     CCCCCC     |
|EEEEEEE|         |     EEEEEE     |
|FFFFFFF|         |_____GGGGGG_____|
|GGGGGGG|
---------

Here the entire image in the portrait view is scaled to fit in the landscape view when the iPhone rotates. It is also centered. I am also trying to preserve the aspect ratio. User interaction is also on, and the user should be able to use the entire screen to pan/zoom the image.

Currently I have the following autoresizingMask on the scrollView:

 scrollView.autoresizingMask =(UIViewAutoresizingFlexibleWidth |
                               UIViewAutoresizingFlexibleHeight);       

But this gives the following

_________
|AAAAAAA|
|BBBBBBB|         _________________
|CCCCCCC|         |AAAAAA          |
|DDDDDDD|    -->  [BBBBBB          |
|EEEEEEE|         [CCCCCC          |
|FFFFFFF|         [DDDDDD__________|
|GGGGGGG|
---------

This setting preserves scale and offset from upper left corner.

Question: Is it possible to obtain this behaviour using suitable autoresizingMask? If not, one should probably set

 scrollView.autoresizingMask = UIViewAutoresizingNone;

and manually set zoomScale and contentOffset for the UIScrollView on rotation. But, where should that be done? What about animating that change?

Solution: By very slightly modifying the answer below I got the above behaviour using the below code:

imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                     UIViewAutoresizingFlexibleHeight);

scrollView.autoresizingMask =(UIViewAutoresizingFlexibleWidth 
                                     | UIViewAutoresizingFlexibleHeight);

imageView.contentMode = UIViewContentModeScaleAspectFit;
scrollView.contentMode = UIViewContentModeCenter;

Answer

David Liu picture David Liu · Nov 18, 2010

Try this:

scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                           UIViewAutoresizingFlexibleHeight);    
imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                           UIViewAutoresizingFlexibleHeight);

imageView.contentMode = UIViewContentModeAspectFit; // You could also try UIViewContentModeCenter

I'm not sure if the imageView will get automatically resized within a UIScrollView, so if the autoresizing doesn't work, you could try setting the frame yourself on rotate to equal the size of the scrollview.