简体   繁体   中英

UIImageView does not follow device orientation

I have a scrollView with several subViews. The subViews are defined like this:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGRect rect = imageView.frame;
rect.size.height = screenRect.size.height;
rect.size.width = screenRect.size.width;
imageView.frame = screenRect;
[scrollView addSubview:imageView];

This works fine until I change the interface orientation to landscape. The imageView is still in portrait mode, cutting the image in half. What should I do to change the portrait height and width, to landscape height and width?

Add this line in your code and check:

[imageView setAutoresizesSubviews:YES];
[imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

[imageView setAutoresizesSubviews:YES];
[imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

Check this link too.

A couple of thoughts:

  1. Rather than [[UIScreen mainScreen] bounds] , I use self.view.bounds . This (a) will factor out things like status bars, navigation bars, etc.; and (b) upon rotation, the width and height are automatically updated to reflect the new dimensions.

  2. If you want your imageview to be resized for you, you generally set its autoresizingMask to something like UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth .

  3. You might want to check your imageview's contentMode and set it to something like UIViewContentModeScaleAspectFit so your whole image will always be displayed. That way, if you have a portrait image, it will always show up in portrait without distortion, without being cut off.

  4. If you don't like the fact that your image view, itself, has been resized to landscape when you rotate the device, you can reset its frame in viewWillLayoutSubviews in iOS5 (in iOS4, use willAnimateRotationToInterfaceOrientation ).

You need to listen for a UIDeviceOrientationDidChangeNotification

read more about that here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html

Once you detect the change, call the same code again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM