Adding a Texture to a Sprite in SpriteKit

When you add a sprite to a SpriteKit scene from the scene editor, the only option is to create a sprite with a single color. A sprite with one color is OK for prototyping. But you’re going to eventually need to use real images for your sprite. Textures are the way to apply an image to a sprite so it looks like a spaceship, car, person, animal, or whatever your game needs. In this article you’ll learn how to add textures to your SpriteKit project and apply a texture to a sprite.

Add the Images to the Project

The first step to using textures is to add the texture images to the project. Add the images to the asset catalog.

  1. Select the Assets.xcassets folder on the left side of the project window.
  2. Click the Add button, which is at the bottom of the list of assets in the catalog.
  3. Choose Import from the menu that opens when you click the Add button to add an image.

You can also choose Image Set from the menu. Drag the image to the 1x, 2x, or 3x image well. What do 1x, 2x, and 3x mean?

  • A 1x image is for non-retina screens. Only very old iOS devices have non-retina screens.
  • A 2x image is for retina screens.
  • A 3x image is for super-retina screens on newer iOS devices.

Supporting 1x, 2x, and 3x means you need three copies of each image. If you have a texture image that is 128 by 128 pixels, you must supply the following images:

  • The 128 by 128 pixel version for 1x
  • A 256 by 256 pixel version for 2x
  • A 384 by 384 pixel version for 3x

Assign a Texture to a Sprite

After adding the texture images to the asset catalog, you can apply a texture to the sprite.

  1. Open the scene (.sks file) that contains the sprite.
  2. Select the sprite.
  3. Open the attributes inspector.
  4. Choose the texture from the Texture combo box.

Now the sprite looks like the texture image instead of one solid color.

You can create a sprite in code and use the texture image by calling the SKSpriteNode initializer and supplying the name of the image as the imageNamed: argument.

The name of the image must match the name in the asset catalog.