Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting actual view size in Swift / IOS

Tags:

xcode

ios

swift

Even after reading several posts in frame vs view I still cannot get this working. I open Xcode (7.3), create a new game project for IOS. On the default scene file, right after addChild, I add the following code:

    print(self.view!.bounds.width)
    print(self.view!.bounds.height)

    print(self.frame.size.width)
    print(self.frame.size.height)

    print(UIScreen.mainScreen().bounds.size.width)
    print(UIScreen.mainScreen().bounds.size.height)

I get following results when I run it for iPhone 6s:

 667.0
 375.0
 1024.0
 768.0
 667.0
 375.0

I can guess that first two numbers are Retina Pixel size at x2. I am trying to understand why frame size reports 1024x768 ?

Then I add following code to resize a simple background image to fill the screen:

    self.anchorPoint = CGPointMake(0.5,0.5)

    let theTexture = SKTexture(imageNamed: "intro_screen_phone")
    let theSizeFromBounds = CGSizeMake(self.view!.bounds.width, self.view!.bounds.height)
    let theImage = SKSpriteNode(texture: theTexture, color: SKColor.clearColor(), size: theSizeFromBounds)

I get an image smaller than the screen size. Image is displayed even smaller if I choose landscape mode.

I tried multiplying bounds width/height with two, hoping to get actual screen size but then the image gets too big. I also tried frame size which makes the image slightly bigger than the screen.

Main reason for my confusion, besides lack of knowledge is the fact that I've seen this exact example on a lesson working perfectly. Either I am missing something obvious or ?

like image 423
Charles Avatar asked Mar 31 '16 21:03

Charles


1 Answers

The frame is given as 1024x768 because it is defined in points, not pixels.

If you want your scene to be the same size as your screen, before the scene is presented in your GameViewController, before:

skView.presentScene(scene)

use this:

scene.size = self.view.frame.size

which will make the scene the exact size of the screen.

Then you could easily make an image fill the scene like so:

    func addBackground() {

        let bgTexture = SKTexture(imageNamed: "NAME")

        let bgSprite = SKSpriteNode(texture: bgTexture, color: SKColor.clearColor(), size: scene.size)
        bgSprite.anchorPoint = CGPoint(x: 0, y: 0)
        bgSprite.position = self.frame.origin
        self.addChild(bgSprite)
    }

Also, you may want to read up on the difference between a view's bounds and it's frame.

like image 177
Wes Avatar answered Oct 18 '22 18:10

Wes