iOS get physical screen size programmatically?

前端 未结 11 1922
情话喂你
情话喂你 2020-12-15 03:11

Is this possible? I want the number of inches, not the number of pixels. I know it is approximately 160 ppi. But not exactly.

相关标签:
11条回答
  • 2020-12-15 03:30

    There isn't an API that will give you this. Your best bet is to look at the device's screen size (in points) and from that surmise if it's an iPad or iPhone etc., and then use hard-coded values for the screen sizes.

    Here's some code to get the screen size:

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;
    

    Be aware that width and height might be swapped, depending on device orientation.

    0 讨论(0)
  • 2020-12-15 03:30

    Since this question has been asked, I’ve created an open-source library to handle this problem: IRLSize. It can be used in either direction: to measure the size of a view (or the whole screen) in real-world dimensions, or to set the size of a view to a specific real-world dimension.

    0 讨论(0)
  • 2020-12-15 03:40

    note: screen rotation matters here

    extension UIScreen {
        var physicalSize:CGSize {
            return CGSize(width: bounds.width*scale, height: bounds.height*scale)
        }
    }
    

    using:

    print(UIScreen.main.physicalSize)
    
    0 讨论(0)
  • 2020-12-15 03:40

    Here is a Swift way to get screen sizes:

    var screenWidth: CGFloat {
        if UIInterfaceOrientationIsPortrait(screenOrientation) {
            return UIScreen.mainScreen().bounds.size.width
        } else {
            return UIScreen.mainScreen().bounds.size.height
        }
    }
    var screenHeight: CGFloat {
        if UIInterfaceOrientationIsPortrait(screenOrientation) {
            return UIScreen.mainScreen().bounds.size.height
        } else {
            return UIScreen.mainScreen().bounds.size.width
        }
    }
    var screenOrientation: UIInterfaceOrientation {
        return UIApplication.sharedApplication().statusBarOrientation
    }
    

    These are included as a standard function in:

    https://github.com/goktugyil/EZSwiftExtensions

    0 讨论(0)
  • 2020-12-15 03:48

    You might need use [UIScreen mainScreen].scale;

    CGFloat scale = [UIScreen mainScreen].scale;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    CGFloat physicalWidth = screenRect.size.width * scale;
    CGFloat physicalHeight = screenRect.size.height * scale;
    
    0 讨论(0)
  • 2020-12-15 03:48

    Nobody said about fixedCoordinateSpace. In Swift 3 to get the screen dimensions in a portrait-up orientation you should use: UIScreen.main.fixedCoordinateSpace.bounds

    0 讨论(0)
提交回复
热议问题