开发者

What is the correct way to get screen width/height with orientation changes?

I'm currently using [[UIScreen mainScreen] bounds].size.width and height to get the screen width and height for getting a new image (that fills the screen) from a server. My problem is it appears that the bounds doesn't change on orientation changes. So if I rotate the device 开发者_如何学编程then it still gives me portrait width/heights even though the device is now in landscape. I'd like to not hardcode a screen width/height based on the current orientation. Is there a way that I can check the screen width and height that will correctly reflect orientation changes?


You can get the width and height by

int h = self.view.frame.size.height;
int w = self.view.frame.size.width;


Best way to do this is probably:

CGSize appSize = [UIApplication sharedApplication].keyWindow.rootViewController.view.bounds.size;

and also use appSize.height for height and appSize.width for width This returns the orientation adjusted size of the topmost view which always fills the full screen, except possibly excluding the status bar depending on your status bar and wantsFullscreen settings.


[UIScreen mainScreen].bounds.size returns the bounds unrotated. You can use the convertRect:fromView: method (passing nil for the fromView) on an appropriate on-screen UIView to adjust for rotation and such.


I've been working on an app where we have run into problems like this on a few occasions, so I hope I can help:

  1. First off, make sure you are using a UIViewController to manage your image.
  2. Secondly, make sure your implementation of -shouldAutorotateToInterfaceOrientation: on that view controller returns YES.
  3. Make sure you are using a UIImageView, not a UIImage for your picture, then try setting autoresizesSubviews on the image view's superview (this is the view controller's view) to YES.
  4. If the image resizes, but not to your liking, try messing with the image view's autoresizingMask.
  5. If, after step 3, the image doesn't autoresize, try implementing willRotateToInterfaceOrientation:duration: and programmatically setting the image's frame. Remember that it's superview (the UIViewController's view) hasn't rotated yet, so its frame hasn't updated.
  6. Finally, if that doesn't work, try willAnimateRotationToInterfaceOrientation:duration:, though I'm not quite clear on the difference between this method and the former.

Hope this helps, and let me know your results!

-Bruce


try get your height and width from applicationFrame

UIScreen.mainScreen().applicationFrame.size.height

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜