FREE: Watch my new YouTube videos, Xcode in 20 Seconds! >>

How to change a sprite’s texture using SKTexture

Paul Hudson       @twostraws

Although you can create an SKSpriteNode from a color and size, most folks create them from textures – image data stored in an asset catalog or texture atlas. SpriteKit’s textures are handled using their own class called SKTexture, and you can load them individually then use them to change the texture used to draw a sprite.

At its most basic, you can change a sprite’s texture like this:

let texture1 = SKTexture(imageNamed: "newTexture")
someSprite.texture = texture1

However, that only works if your sprite and the texture are the same size – if they don’t, the texture will get squashed to fit the available space.

If the sprite and texture are different sizes then a better thing to do is use the setTexture() action, passing in true for its resize parameter like this:

let texture2 = SKTexture(imageNamed: "newTexture")
let action = SKAction.setTexture(texture2, resize: true)
someSprite.run(action)

That will switch the texture over, then grow the sprite to fit the new texture size.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!

Available from iOS 7.1

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Build for watchOS

Take your existing Swift skills to Apple's tiniest platform – check out Hacking with watchOS!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>