在纵向和横向模式下获取相同的屏幕宽度和高度

6

我使用了这段代码获取屏幕宽度和高度:

    float scaleFactor = [[UIScreen mainScreen] scale];
    CGRect screen = [[UIScreen mainScreen] bounds];
    CGFloat widthInPixel = screen.size.width * scaleFactor;
    CGFloat heightInPixel = screen.size.height * scaleFactor;

    NSLog(@"%f",widthInPixel);
    NSLog(@"%f",heightInPixel);

并且

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    NSLog(@"screenBounds W %f",screenBounds.size.width);
    NSLog(@"screenBounds H %f",screenBounds.size.height);

但在横屏和竖屏模式下,它显示的宽度和高度都是相同的,都为width=768和height=1024。


请参考此答案:https://dev59.com/NVbTa4cB1Zd3GeqP7A3F - crz
4个回答

16

这将为您提供良好的解释 - 如何获得依赖方向的屏幕高度和宽度?

另外一种定义宏的方法是通过以下方式建议:这里有一个方便的宏:.

#define SCREEN_WIDTH (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
#define SCREEN_HEIGHT (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)

0
那是因为你正在使用 mainScreen,没有考虑到设备的方向。除非你实现一个记录所有方向的方法,否则它最终会一直返回相同的值。
尝试像这样做:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) 
{       
//log here

} else {
// log here
}

0

您想在旋转设备或在横向模式下运行应用程序时获取宽度和高度吗?

如果您正在旋转设备,则永远不会在didRotateToInterfaceOrientation中获取新的宽度和高度。

您需要重写viewWillLayoutSubviews方法,在那里您将获得新的宽度和高度,并且可以在那里检查设备方向是否更改,您可以使用新的尺寸。因为每次视图更改时都会调用viewWillLayoutSubviews,所以在实现该函数之前,请注意阅读苹果文档。


0

尝试从applicationFrame获取您的高度和宽度

var h = UIScreen.mainScreen().applicationFrame.size.height

var w = UIScreen.mainScreen().applicationFrame.size.Width


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接