Tom Xue Tom Xue - 1 month ago 11
iOS Question

Swift - Add a background image to a Spritekit scene

Here's my code, i didn't use asset catalog for my image InterfaceBakground.jepg. Instead, I just dragged this 2048x1535 image to the project. But the image didn't appear the right way. I want the image to display as the background image, fill the entire screen.

import SpriteKit
import GameplayKit
class GameScene: SKScene {

var background = SKSpriteNode(imageNamed: "InterfaceBakground.jpeg")


override func didMove(to view: SKView) {
background.position = CGPoint(x: self.size.height/2, y: self.frame.width/2)

self.addChild(background)
}

override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}


I saw this on the internet which brings me a little inspiration:


But if you’re using an image that is exactly the size of the screen,
it may not appear where you expect. This is because addChild adds new
sprites at position 0, 0 (bottom left corner) by default. If you want
to use an image sized specifically for your screen, you’ll have to
change its position.


My question is, how to change the position, so it fits devices for different size displays? Thanks in advance.

Joe Joe
Answer

Try this code:

override func didMove(to view: SKView) {
    background.position = CGPoint(x: 0, y: 0)
    background.size.width = self.size.width
    background.size.height = self.size.height
    background.anchorPoint = CGPoint(x: 0.5,y: 0.5)

    self.addChild(background)
}

AnchorPoint (0.5,0.5) which centers the image in its position.

Comments