SpriteKit how to get correct screen size
Asked Answered
L

2

11

I've tried

self.frame.size
self.view!.frame.size
UIScreen.mainScreen().bounds.size

None of them work.

How do I get the correct screen size for the device?

Lingenfelter answered 18/12, 2015 at 6:27 Comment(3)
Where are you checking those properties? didMoveToView?Grab
yup, over there. @0x0141ELingenfelter
How does UIScreen.mainScreen().bounds.size not get you the correct size? the reason self.frame and self.view.frame does not get you the correct size is because self.frame is the size of the scene, which is usually 600x600 and self.view.frame is the size of the view before autolayout get applied, so it is probably 600x600 alsoGizela
C
15

You can use following swift code to get the screen size.

let displaySize: CGRect = UIScreen.mainScreen().bounds
let displayWidth = displaySize.width
let displayHeight = displaySize.height
Clap answered 18/12, 2015 at 7:6 Comment(1)
in Swift 4 it is let displaySize: CGRect UIScreen.main.boundsCharleen
C
5

You can use:

let deviceWidth = UIScreen.mainScreen().bounds.width
let deviceHeight = UIScreen.mainScreen().bounds.height

And if you need to get the ratio so you can detect what device they are using, you can use the following for portrait mode or switch it for landscape mode.

let maxAspectRatio: CGFloat = deviceHeight / deviceWidth

You can then check what ratio the device is to determine certain things.

if maxAspectRatio == (4 / 3) {
    //The ratio of an iphone 4S is 4:3
    print("The user is using an iPhone 4S or iPod 4th Generation.")
} else if maxAspectRatio >= 1.7 && maxAspectRatio <= 1.8 {
    //The ratio of these devices is 16:9
    print("The user is using an iPhone 5, 5S, 5C, 6, 6S, 6 Plus, 6S Plus, or iPod 5th Generation.)
} else {
    print("The user is using an iPad, iPad Mini, iPad Air, iPad Retina, or iPad Pro.")
}

If you want to get the correct view that the player can see, as in the bounding frame of the device's size, you can use the following guide.

Cadelle answered 19/12, 2015 at 7:44 Comment(1)
broken link! =[Brume

© 2022 - 2024 — McMap. All rights reserved.