Kingfisher
Kingfisher copied to clipboard
Support animated images (like GIFs) in SwiftUI
Currently, the SwiftUI integration does not support animated images at all. It seems like the easiest thing to do would be just to use the existing AnimatedImageView wrapped in UIViewRepresentable if the image is animated.
This would be really great to have since there aren't any other good solutions for SwiftUI GIFs at the moment.
It's a nice idea and easy way to wrap AnimatedImageView using UIViewRepresentable, for supporting SwiftUI GIFs animated image display.
@available(iOS 13.0, *)
struct KFAnimatedImage: UIViewRepresentable {
var resource: Resource?
func makeUIView(context: Context) -> AnimatedImageView {
return AnimatedImageView()
}
func updateUIView(_ uiView: AnimatedImageView, context: Context) {
uiView.kf.setImage(with: resource)
}
}
Usage:
@available(iOS 13.0, *)
struct AnimatedImageDemo: View {
var body: some View {
KFAnimatedImage(resource: ImageLoader.gifImageURLs.first!)
}
}
It works.
Though, we could try a more SwiftUI way to implement a KFAnimatdImage. 👀
@Binlogo Thanks for pointing it out and these code snippets.
Actually it is not hard to wrap it as a UIViewRepresentable
. Providing all the supported options is also possible and I will try to add it to Kingfisher later. (If you already have a version, I am glad to receive a PR!)
Though, we could try a more SwiftUI way to implement a
KFAnimatdImage
. 👀
We can try to make the API of the wrapper type better in SwiftUI, but implementing it all by SwiftUI is not an option. It is not that fitting in the today's SwiftUI concept yet, at least for now, I am afraid.
@onevcat I just made a quick demo, if wrapping the AnimatedImageView
as UIViewRepresentable
is ok, I'd like to have a try to provide a rough PR for discussion.
How would you set/call the resizable
property on a KFANimatedImage? The modifier doesn't seem to exist, but I'm not sure if it's accessible through another property on KFANimatedImage?
E.g normally I'd do this to render an image:
KFImage(url).resizable()
Thanks!
@sslash I guess you just do not need that. It is a UIView
under the hood and can handle resizing automatically for you:
Thanks for replying @onevcat ! That was what I was looking for, although I'm struggling to get what I want still, when I try to wrap the image in a ClipPath with rounded corners. But that's just me being a bit of a newbie I guess 😄
is there anyway to use this animated image when the resource is available as gif in app resources ?
KFAnimatdImage
also accepts a Source
, so you can use a local file "provider" to send a resource to the animated image.
KFAnimatedImage(source:
.provider(LocalFileImageDataProvider(fileURL: your_resource_url))
)
Since the support of GIF was already implemented in Kingfisher, I am closing this.
Is there any way to control stating animation and stop it depend on tap gesture