Erika
Erika

Reputation: 255

Add GIF to Swift Playground

I have an SKScene in a Swift Playground and I want to add this gif (https://media.giphy.com/media/uMU6E2DFqeZSE/giphy.gif) to the background as an SKSpriteNode. I first tried converting it as an animated UIImage into an SKSpriteNode as shown below:

let dance = UIImage.animatedImageNamed("macarenadance.gif", duration: 3.0)
let texture = SKTexture(image: dance!)
let testImage = SKSpriteNode(texture: texture)
scene.addChild(testImage)

But it encountered a conversion error and stopped midway through running. It seems as it's not possible to use an animated UIImage as a sprite. Any suggestions/alternatives to displaying the gif in the Swift Playground would be greatly appreciated.

Upvotes: 1

Views: 1180

Answers (2)

E.Coms
E.Coms

Reputation: 11537

Maybe you have to use separated images for SKTextureAnimations:

   let texture = SKTexture.init(imageNamed: "macarenadance0.png")
   let texture1 = SKTexture.init(imageNamed: "macarenadance1.png")
   let texture2 = SKTexture.init(imageNamed: "macarenadance2.png")

    let textures = [texture,texture1,texture2]

    let testImage = SKSpriteNode(texture: texture);

    testImage.run(SKAction.repeatForever(
       SKAction.animate(with: textures, timePerFrame: 0.3)))
   addChild(testImage)

Upvotes: 0

Matic
Matic

Reputation: 501

UIImage unfortunately does not support gif animation, but luckily enough, there is 3rd party library to help you out.

It's called SwiftGif.

Below is the example usage. Add the file to the source of the playground and paste this in:

import UIKit
import PlaygroundSupport



let image = UIImage.gif(name: "yourgifgoeshere.gif")

PlaygroundPage.current.liveView = imageView

Upvotes: 1

Related Questions