SwiftUI: Assign the height of the screen safe area in pixels to a constant

I want to programmatically determine the height of the safe area of the screen in pixels and save this value as a constant (in much the same way as "UIScreen.main.nativeBounds.height" returns the full height of the screen in pixels). I've done searches for this but most answers I found use deprecated instructions and don't work. I'm using SwiftUI. I also tried GeometryReader without success. Using ".offset(y: geometry.size.height)" with GeometryReader moved the image however replacing that line with "let scrnHeight = geometry.size.height" produced a compile error back on the GeometryReader definition line. Various tweaks to the line defining the constant gave the same result. I don't want to move or change the image, I just want the height value. The reason I want this constant is for scaling various images, placing them at the correct point on the screen and for defining their speed around the screen. I have an image which is imported to fit the height of the screen safe area in the background. The height of this equates to 400 metres - therefore the pixel height for any iPhone or iPad will be (400m/(height of safe area in pixels)). The system clearly knows this figure as the imported image fits the safe area precisely using ".aspectRatio(contentMode: .fill). I simply need to access the value. Any help would be appreciated - thanks!

Answered by Claude31 in 678263022

To convert points to pixels, use: UIScreen.main.scale

See details here: https://stackoverflow.com/questions/48737789/how-do-i-figure-out-pixel-to-point-conversion-on-specific-iphone

Note: when you write your post, please edit it so that it is more readable. 12 packed lines is pretty hard to read.

ps. I have managed to get the height in points using GeometryReader but would still prefer to know the height in pixels. Anybody?

Accepted Answer

To convert points to pixels, use: UIScreen.main.scale

See details here: https://stackoverflow.com/questions/48737789/how-do-i-figure-out-pixel-to-point-conversion-on-specific-iphone

Note: when you write your post, please edit it so that it is more readable. 12 packed lines is pretty hard to read.

SwiftUI: Assign the height of the screen safe area in pixels to a constant
 
 
Q