Skip to content

Instantly share code, notes, and snippets.

@bitops
Created November 1, 2022 22:05
Show Gist options
  • Save bitops/770e586d62090d373ab22c923fa50bd2 to your computer and use it in GitHub Desktop.
Save bitops/770e586d62090d373ab22c923fa50bd2 to your computer and use it in GitHub Desktop.
A SwiftUI View that renders gifs using ImageIO
import SwiftUI
import ImageIO
struct TestGif {
static let url: URL = Bundle.main.url(forResource: "your-file-here", withExtension: "gif")!
}
struct GifView: View {
@State private var gif: UIImage
private let gifImageUrl: CFURL
init(gifUrl: URL) {
gifImageUrl = gifUrl as CFURL
let sourceOptions = [ kCGImageSourceShouldCache: false ] as CFDictionary
let imageSource = CGImageSourceCreateWithURL(gifImageUrl as CFURL, sourceOptions)!
let downSampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true
] as CFDictionary
let scaledImage: CGImage = CGImageSourceCreateThumbnailAtIndex(
imageSource, 0, downSampleOptions
)!
gif = UIImage(
cgImage: scaledImage
)
}
var body: some View {
Image(uiImage: gif)
.resizable()
.onAppear(perform: beginAnimation)
}
private func beginAnimation() {
CGAnimateImageAtURLWithBlock(gifImageUrl, .none) { int, cgImage, bool in
self.gif = UIImage(cgImage: cgImage)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
GifView(gifUrl: TestGif.url).frame(width: 200, height: 200)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment