Adding a Texture to a Sprite in SpriteKit
Table of Contents
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.
The first step to using textures is to add the texture images to the project. Add the images to the asset catalog.
- Select the
Assets.xcassets
folder on the left side of the project window. - Click the Add button, which is at the bottom of the list of assets in the catalog.
- 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
After adding the texture images to the asset catalog, you can apply a texture to the sprite.
- Open the scene (.sks file) that contains the sprite.
- Select the sprite.
- Open the attributes inspector.
- 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.
var sprite = SKSpriteNode(imageNamed: "TestTexture")
The name of the image must match the name in the asset catalog.