主页 Swift UNIX C Assembly Go Plan 9 Web MCU Research Non-Tech

How to get the screen size (bounds and nativeBounds) in Swift/SwiftUI

2022-11-07 | Swift | #Words: 346

This blog was originally published on 2021-02-07 17:12:03, but due to a modification (or say a bug, which I has been reported) discovered on 2022-11-6, so I add something about that. For details, please see: The height of UIScreen.main.bounds occurs change (not right value)​.

bounds

There are something you must notice, please check the link above.

var screenBounds:CGRect = UIScreen.main.bounds

The unit of UIScreen.main.bounds is point.

var width: CGFloat = UIScreen.main.bounds.width
var height: CGFloat = UIScreen.main.bounds.height

Now you can get screen size in CGFloat. You can use this value to drawing some UIs, such as drawing grids and moving the position of components.

The reason why bound for drawing and moving component positions is View generally uses CGFloat format data for operations. If you use nativeBounds, there is no way to operate because points and pixels is not one-to-one correspondence. And because the range is slightly “loose”, this can effectively avoid errors caused by rounding during calculation.

nativeBounds

var screenBounds: CGRect = UIScreen.main.nativeBounds

nativeBounds is in pixel.

var width: CGFloat = UIScreen.main.nativeBounds.width
var height: CGFloat = UIScreen.main.nativeBounds.height

Use this method you can get size in CGFloat, but usually use it to get the size of some View or entire screen. Drawing View or move components do not use it usually.

Below is the values of iPhone 11 Pro:

  bounds nativeBounds
width 375 812
height 1125 2436

I hope these will help someone in need~