Skip to content

Instantly share code, notes, and snippets.

@Enie
Last active September 5, 2023 20:32
Show Gist options
  • Save Enie/a09d6b17e8a6ecc579cd89aaad0da492 to your computer and use it in GitHub Desktop.
Save Enie/a09d6b17e8a6ecc579cd89aaad0da492 to your computer and use it in GitHub Desktop.
Rendering animated gifs in SwiftUI.
import SwiftUI
public struct AnimatedImage: NSUIViewRepresentable {
public let animationImage: NSUIImage
public let isAnimating: Bool
#if os(iOS) || os(watchOS) || os(tvOS)
public func makeUIView(context: Context) -> UIImageView {
let imageView = UIImageView()
imageView.image = animationImage
return imageView
}
public func updateUIView(_ uiView: UIImageView, context: Context) {
if isAnimating {
uiView.stopAnimating()
} else {
uiView.startAnimating()
}
}
typealias UIViewType = UIImageView
#elseif os(macOS)
public func makeNSView(context: Context) -> NSImageView {
let nsImageView = NSImageView()
nsImageView.wantsLayer = true
nsImageView.canDrawSubviewsIntoLayer = true
nsImageView.imageScaling = .scaleProportionallyUpOrDown
nsImageView.animates = false
nsImageView.image = animationImage
return nsImageView
}
public func updateNSView(_ nsView: NSImageView, context: Context) {
if isAnimating {
nsView.animates = true
} else {
nsView.animates = false
}
}
#endif
public func makeCoordinator() -> Coordinator {
Coordinator(self)
}
public class Coordinator {
public var parent: AnimatedImage
init(_ parent: AnimatedImage) {
self.parent = parent
}
}
}
struct NSAnimatedImage_Previews: PreviewProvider {
static var previews: some View {
AnimatedImage(animationImage: NSImage(urlToGif), isAnimating: true)
}
}
import SwiftUI
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
public typealias NSUIImage = UIImage
public typealias NSUIViewRepresentable = UIViewRepresentable
#elseif os(macOS)
import AppKit
public typealias NSUIImage = NSImage
public typealias NSUIViewRepresentable = NSViewRepresentable
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment