SwiftUI display gif image
Easiest and fastest way to display gif image in swiftUI - is to use Preview
/ QuickLook (QL)
/ QLPreviewView
Quartz available only in macOS 10.4+ https://developer.apple.com/documentation/quartz
import SwiftUI
import Quartz
struct QLImage: NSViewRepresentable {
var url: URL
func makeNSView(context: NSViewRepresentableContext<QLImage>) -> QLPreviewView {
let preview = QLPreviewView(frame: .zero, style: .normal)
preview?.autostarts = true
preview?.previewItem = url as QLPreviewItem
return preview ?? QLPreviewView()
}
func updateNSView(_ nsView: QLPreviewView, context: NSViewRepresentableContext<QLImage>) {
nsView.previewItem = url as QLPreviewItem
}
typealias NSViewType = QLPreviewView
}
How to load GIF image in Swift?
Load GIF image Swift :
## Reference.
#1 : Copy the swift file from This Link
:
#2 : Load GIF image Using Name
let jeremyGif = UIImage.gifImageWithName("funny")
let imageView = UIImageView(image: jeremyGif)
imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
view.addSubview(imageView)
#3 : Load GIF image Using Data
let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
let advTimeGif = UIImage.gifImageWithData(imageData!)
let imageView2 = UIImageView(image: advTimeGif)
imageView2.frame = CGRect(x: 20.0, y: 220.0, width:
self.view.frame.size.width - 40, height: 150.0)
view.addSubview(imageView2)
#4 : Load GIF image Using URL
let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
let imageURL = UIImage.gifImageWithURL(gifURL)
let imageView3 = UIImageView(image: imageURL)
imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
view.addSubview(imageView3)
Download Demo Code
OUTPUT :
iPhone 8 / iOS 11 / xCode 9
Animate an animated gif only while pressing the button
As far as I know, SwiftUI doesn't have anything that can do this. Instead, you should use an @State
variable to track whether or not the button has been pressed. If it hasn't, show a non-animated image, and if it has, show a different image, but animated this time.
Something like this:
@State var buttonIsClicked = false
let nonAnimated = <static image>
let animated = <your gif>
var body: some View {
VStack {
if buttonIsClicked {
animated
} else {
nonAnimated
}
Button("Click to animate") {
buttonIsClicked.toggle()
}
}
}
Any way to get a gif as a background with swiftUI?
I've used a WKWebView to display a gif. The resulting view can be set anywhere. To set it as a background, you'll probably want to resize the contents of the WKWebView according to the contents of the superview.
import SwiftUI
import WebKit
struct HTMLRenderingWebView: UIViewRepresentable {
@Binding var htmlString: String
@Binding var baseURL: URL?
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if self.htmlString != context.coordinator.lastLoadedHTML {
print("Updating HTML")
context.coordinator.lastLoadedHTML = self.htmlString
uiView.loadHTMLString(self.htmlString, baseURL: self.baseURL)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: HTMLRenderingWebView
var lastLoadedHTML = ""
init(_ parent: HTMLRenderingWebView) {
self.parent = parent
}
}
}
struct HTMLRenderingWebViewExample: View {
@State var htmlString = ""
var body: some View {
VStack {
HTMLRenderingWebView(htmlString: self.$htmlString, baseURL: .constant(nil))
.padding(30).background(Color.gray)
Button("Click this button") {
self.htmlString = "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" +
(self.assetAsString() ?? "image loading failed")
}
}.navigationBarTitle("Example HTML Rendering")
}
func assetAsString() -> String? {
let asset = NSDataAsset(name: "User_OhSqueezy_on_commons_wikimedia_org_Parallax_scrolling_example_scene")
if let data = asset?.data {
let base64string = data.base64EncodedString()
let format = "gif"
return "<img src='data:image/\(format);base64," + base64string + "' height=240 width=360>"
} else {
return nil
}
}
}
I got my animated gif from Wikimedia Commons and dragged it into the Assets.xcassets
in Xcode.
Result:
How to animate images in SwiftUI, to play a frame animation
I solved this using UIViewRepresentable
protocol. Here I returned a UIView
with the ImageView
as it's subview. This gave me more control over the child's size, etc.
import SwiftUI
var images : [UIImage]! = [UIImage(named: "pushup001")!, UIImage(named: "pushup002")!]
let animatedImage = UIImage.animatedImage(with: images, duration: 0.5)
struct workoutAnimation: UIViewRepresentable {
func makeUIView(context: Self.Context) -> UIView {
let someView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
let someImage = UIImageView(frame: CGRect(x: 20, y: 100, width: 360, height: 180))
someImage.clipsToBounds = true
someImage.layer.cornerRadius = 20
someImage.autoresizesSubviews = true
someImage.contentMode = UIView.ContentMode.scaleAspectFill
someImage.image = animatedImage
someView.addSubview(someImage)
return someView
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<workoutAnimation>) {
}
}
struct WorkoutView: View {
var body: some View {
VStack (alignment: HorizontalAlignment.center, spacing: 10) {
workoutAnimation()
Text("zzzz")
}
}
}
How to load animated GIF from photo library
Yes, Use ALAssetsLibrary → now called PHAsset.
You should get the NSData of the gif, not UIImage( because UIImage will only get the first frame.)
So basically you would do something like this:
One you get the asset
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true // adjust the parameters as you wish
PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, UTI, _, _) in
if let uti = UTI,let data = imageData ,
// you can also use UTI to make sure it's a gif
UTTypeConformsTo(uti as CFString, kUTTypeGIF) {
// save data here
}
})
Resource: PHAsset
Related Topics
Advancedby' in Swift Is Unavailable
How to Make Exponents in the Swiftui
How to Retrieve Audio File from Parse Swift
Swiftui Mysterious Spacing Between Large Text and Textfield in VStack
Cannot Stop Background Music from Within Game Scenes, Swift 3/Spritekit
Let User Save PDF Outside App in iOS Swift
Declaring Conformance to @Objc Protocol in Empty Extension Breaks with Exc_Bad_Instruction
Swift: Can't Edit Properties of Custom Table Cell Programmatically
Comparing Objects in an Array Extension Causing Error in Swift
How to Inject .Environmentobject() in Watchos6
How to Change the Appearance of the Datepicker in the Swiftui Framework to Only Months and Years
How to Call a Func Within a Closure
Ios13 Uialertcontroller with Custom View & Preferredstyle as Actionsheet Grayscale All Colors
How to Compare Two Strings to Check If They Have Same Characters Swift 4