【问题标题】:Making a GIF from images using Swift (macOS)使用 Swift (macOS) 从图像制作 GIF
【发布时间】:2016-12-19 20:17:49
【问题描述】:

我想知道是否有办法在 macOS/osx 中使用 Swift 转换 NSImage 数组?

之后我应该能够将其导出到文件中,因此在我的应用上显示的图像动画是不够的。

谢谢!

【问题讨论】:

  • 这取决于您所说的“有没有办法”。从某种意义上说,您可以自己编写“方法”,但我认为在 Foundation 或 Cocoa 中没有任何类似于 NSGIF(imageSequence:) 的 API。
  • 我明白了。你认为我能找到一个易于实现的库或示例代码吗?
  • 其实,你可能想看看Image I/O框架(example)。

标签: swift macos cocoa gif


【解决方案1】:

Image 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)

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2020-02-21
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多