添加简单的动画GIF到iOS Spritekit游戏?

时间:2014-07-19 23:06:59

标签: ios objective-c animated-gif

我是初学程序员,正在使用iOS sprite-kit创建游戏。我有一个简单的动画GIF(30帧)保存为.gif文件。在我的游戏中显示这个GIF有一种简单的方法(几行代码可能类似于通过UIImage添加常规.png)吗?我已经做了一些关于在Xcode中显示动画GIF的研究,大多数都涉及导入大量的课程,其中大部分都是我认为不需要的东西(我几乎不知道要筛选它)。

2 个答案:

答案 0 :(得分:3)

我认为它的方式就像GIF动画一样。所以我要做的是将gif作为纹理添加到for循环中的SKSpriteNode中,然后告诉它使用SKAction.repeatActionForever()在设备上运行。 说实话,我也很新。我只是想尽力回答。这是用Swift编写的,但我认为它很难转换为Objective-C。

var gifTextures: [SKTexture] = [];

    for i in 1...30 {
        gifTextures.append(SKTexture(imageNamed: "gif\(i)"));
    }

    gifNode.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(gifTextures, timePerFrame: 0.125)));

答案 1 :(得分:1)

Michael Choi的回答将让你在那里一半。剩下的就是从gif文件中获取各个帧。这是我如何做到的(在Swift中):

func load(imagePath: String) -> ([SKTexture], TimeInterval?) {
    guard let imageSource = CGImageSourceCreateWithURL(URL(fileURLWithPath: imagePath) as CFURL, nil) else {
        return ([], nil)
    }

    let count = CGImageSourceGetCount(imageSource)
    var images: [CGImage] = []

    for i in 0..<count {
        guard let img = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
        images.append(img)
    }

    let frameTime = count > 1 ? imageSource.delayFor(imageAt: 0) : nil

    return (images.map { SKTexture(cgImage: $0) }, frameTime)
}

extension CGImageSource { // this was originally from another SO post for which I've lost the link. Apologies.

    func delayFor(imageAt index: Int) -> TimeInterval {
        var delay = 0.1

        // Get dictionaries
        let cfProperties = CGImageSourceCopyPropertiesAtIndex(self, index, nil)
        let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
        if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
            return delay
        }

        let gifProperties: CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)

        // Get delay time
        var delayObject: AnyObject = unsafeBitCast(
            CFDictionaryGetValue(gifProperties,
                                 Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
            to: AnyObject.self)
        if delayObject.doubleValue == 0 {
            delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
                                                             Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
        }

        delay = delayObject as? TimeInterval ?? 0.1

        if delay < 0.1 {
            delay = 0.1 // Make sure they're not too fast
        }

        return delay
    }

}

请注意,我假设gif的每个帧都是相同的长度,但情况并非总是如此。

您还可以使用这些图片轻松构建SKTextureAtlas