I'm using the NSImageView.animates property to play a GIF in SwiftUI as follows:
struct GIFView: NSViewRepresentable {
var gifName: String
func updateNSView(_ nsView: NSView, context: NSViewRepresentableContext<GIFView>) { }
func makeNSView(context: Context) -> NSView {
return GIFPlayerView(gifName: gifName)
}
}
class GIFPlayerView: NSView {
private let imageView = NSImageView(frame: CGRectMake(0,0,200,200))
convenience init(gifName: String) {
self.init()
let asset = NSDataAsset(name: gifName)!
let gif = NSImage(data: asset.data)!
imageView.animates = true
imageView.image = gif
self.addSubview(imageView)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
This works, but the playback speed is slower than I would like. I tried converting the image data into an NSBitmapImageRep and changing the currentFrameDuration for each frame, but it doesn't seem to have any effect on the actual playback speed:
let asset = NSDataAsset(name: gifName)!
let bitmap = NSBitmapImageRep(data: asset.data)!
let count = bitmap.value(forProperty: .frameCount) as! Int
for i in 0..<count {
bitmap.setProperty(.currentFrame, withValue: NSNumber(value: i))
bitmap.setProperty(.currentFrameDuration, withValue: NSNumber(value: 0.01))
}
let gif = NSImage.init(size: bitmap.size)
gif.addRepresentation(bitmap)