【问题标题】:SwiftUI display gif imageSwiftUI 显示 gif 图像
【发布时间】:2022-01-18 23:43:39
【问题描述】:

swiftUI中gif动画图片的显示方式

因为图片

Image("fall-leaves")

不支持 gif 格式

在下面回答

【问题讨论】:

    标签: swift macos image swiftui animated-gif


    【解决方案1】:

    在 swiftUI 中显示 gif 图像最简单、最快的方法是使用 Preview / QuickLook (QL) / QLPreviewView

    Quartz 仅适用于 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
    }
    

    【讨论】:

    • 在您的应用中需要或使用 gif 的位置和原因?
    • @swiftPunk hah) 目前我正在开发另一个应用程序 - 图像查看器 :) 但我也会在 taoGit 中使用这个东西 - 预览提交的图像。所以这段代码在两个项目中都很有用
    • 我能理解的唯一用例是将它用作聊天应用程序中的头像图像或其他东西,但这甚至没有必要。额外不必要的功能。
    • @swiftPunk 这对开发人员来说是不必要的功能。但不适用于 UI 设计师或图形艺术家 :) 你在 git 上看起来就像一个开发人员。但是 git 也可以用于其他职业。如果 git-client 足够容易使用 ofc
    • 关于用例,我必须补充一点,gif 对于作为消息发送也很重要,我差点忘了那个。 :)
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2020-09-19
    • 2020-06-01
    • 2011-06-17
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    相关资源
    最近更新 更多