2016-08-12 85 views
2

我想知道是否有方法在macOS/osx中使用Swift转换NSImages数组?使用Swift从图像制作GIF(macOS)

我应该可以将它导出到文件后,所以在我的应用程序上显示的图像动画将不够。

谢谢!

+1

这取决于你的意思是“有没有办法”。从某种意义上说,“有一种方法”,您可以自己编写代码,但我不认为在Foundation或Cocoa中有任何类似'NSGIF(imageSequence:)'的API。 – zneak

+0

我明白了。你认为我可以找到一个容易实现的库,或示例代码? –

+0

实际上,您可能需要查看[Image I/O](https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/ImageIORefCollection/index.html#//apple_ref/doc/uid/TP40005102)框架([示例](http://stackoverflow.com/questions/14915138/create-and-export-an-animated-gif-via-ios))。 – zneak

回答

2

图像I/O具有您需要的功能。试试这个:

var images = ... // init your array of NSImage 

let destinationURL = NSURL(fileURLWithPath: "/path/to/image.gif") 
let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)! 

// The final size of your GIF. This is an optional parameter 
var rect = NSMakeRect(0, 0, 350, 250) 

// This dictionary controls the delay between frames 
// If you don't specify this, CGImage will apply a default delay 
let properties = [ 
    (kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): 1.0/16.0] 
] 


for img in images { 
    // Convert an NSImage to CGImage, fitting within the specified rect 
    // You can replace `&rect` with nil 
    let cgImage = img.CGImageForProposedRect(&rect, context: nil, hints: nil)! 

    // Add the frame to the GIF image 
    // You can replace `properties` with nil 
    CGImageDestinationAddImage(destinationGIF, cgImage, properties) 
} 

// Write the GIF file to disk 
CGImageDestinationFinalize(destinationGIF)