2014-07-19 63 views
3

我是一名初學者程序員,正在使用iOS sprite-kit創建遊戲。我有一個簡單的動畫GIF(30幀)保存爲.gif文件。有沒有一種簡單的方法(幾行代碼可能類似於通過UIImage添加常規.png)在我的遊戲中顯示此GIF?我已經做了一些關於在Xcode中顯示動畫GIF的研究,並且大多數涉及導入大量的類,其中大部分是我認爲我不需要的東西(我幾乎不知道足以通過它篩選)。添加簡單的動畫GIF到iOS Spritekit遊戲?

+0

http://www.raywenderlich.com/45152/sprite-kit-tutorial-animations-and-texture-atlases –

回答

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))); 
+0

但動畫GIF是一個單一的文件,而在你的代碼中,你假設了一系列單幀圖像文件。 – Bobjt

0

邁克爾崔的回答會讓你一半在那裏。剩下的就是從gif文件中獲取單個幀。下面是我如何做到這一點(斯威夫特):

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