Display Background with Sprite Kit and Swift

Sprite Kit provides a hardware-accelerated animation system which has been optimized for creating 2D games. In this tutorial we will see the Game template in Xcode and add a background image. This tutorial is written in Swift, so Xcode 6 will be needed. It can be downloaded from Apple's developer portal.

Update: Oct 17, 2016. The rewritten version in Swift 3 for iOS 10 and Xcode 8 is available here.

Open Xcode and choose iOS->Application->Game. 

For product name, use SpriteKitSwiftBackgroundTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

In Xcode's Sprite Kit template, a lot of initial work is already been done. In Sprite Kit, a scene controls each “screen” of your app. Navigate to the GameViewController.swift file and in the GameViewController class is the viewDidLoad method defined. Here the scene is created and the Gamescene object is presented.

override func viewDidLoad() {

        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            // Configure the view.
            let skView = self.view as SKView
            skView.showsFPS = true
            skView.showsNodeCount = true
            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true
            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill

We need a background for this tutorial so download our image and add it to the project. Make sure you select the "Copy items if needed" option

Go to the GameScene.swift file. Here is the GameScene class defined. In the didMoveToView method the custom code is done. Delete the code after the "Setup your scene here" comment line and add the following lines

var bgImage = SKSpriteNode(imageNamed: "wallpaper.png")


Sprite Kit has a special class to create and manipulate sprites called SKSpriteNode. In this node our image is loaded. As you can see no file extension is needed. Next, the image is added to our scene. Build and Run the project.

As you can see, not the whole image is presented. This is because by default, a sprite is positioned at (0, 0), which in Sprite Kit represents the bottom left. We can center our image to the screen by adding the following line just before the "self.addChild(bgimage)" line.

bgImage.position = CGPointMake(self.size.width/2, self.size.height/2)

Now Buid and Run again, you will see the image displayed centered on the screen.

You can download the source code of the SpriteKitSwiftBackgroundTutorial at the ioscreator repository on github.