是否可以使用同一张图片通过淡入淡出动画来更改图片? (SwiftUI) [英] Is it possible to change image with fade animation using same Image? (SwiftUI)

查看:218
本文介绍了是否可以使用同一张图片通过淡入淡出动画来更改图片? (SwiftUI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的逻辑,在点击图像时,应使用淡入淡出的动画对其进行更改,但实际结果是图像在没有动画的情况下发生了变化.如果重要,请使用Xcode 11.3.1和Simulator 13.2.2/13.3进行测试.

According to my logic, on tap gesture to the image it should be changed with fade animation, but actual result is that image changes without animation. Tested with Xcode 11.3.1, Simulator 13.2.2/13.3 if it is important.

P.S.图像分别命名为"img1","img2","img3"等.

P.S. Images are named as "img1", "img2", "img3", etc.

enum ImageEnum: String {
    case img1
    case img2
    case img3

    func next() -> ImageEnum {
        switch self {
            case .img1: return .img2
            case .img2: return .img3
            case .img3: return .img1
        }
    }
}

struct ContentView: View {
    @State private var img = ImageEnum.img1
    var body: some View {
        Image(img.rawValue)
            .onTapGesture {
                withAnimation {
                    self.img = self.img.next()
                }
            }
    }
}

推荐答案

以下是使用一个图像的方法(用于演示使用默认图像进行的一些小修改).标有注释的重要更改.

Here is possible approach using one Image (for demo some small modifications made to use default images). The important changes marked with comments.

enum ImageEnum: String {
    case img1 = "1.circle"
    case img2 = "2.circle"
    case img3 = "3.circle"

    func next() -> ImageEnum {
        switch self {
            case .img1: return .img2
            case .img2: return .img3
            case .img3: return .img1
        }
    }
}
struct QuickTest: View {
    @State private var img = ImageEnum.img1
    @State private var fadeOut = false
    var body: some View {
        Image(systemName: img.rawValue).resizable().frame(width: 300, height: 300)
            .opacity(fadeOut ? 0 : 1)
            .animation(.easeInOut(duration: 0.25))    // animatable fade in/out
            .onTapGesture {
                self.fadeOut.toggle()                 // 1) fade out

                // delayed appear
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                    withAnimation {
                        self.img = self.img.next()    // 2) change image
                        self.fadeOut.toggle()         // 3) fade in
                    }
                }
            }
    }
}

这篇关于是否可以使用同一张图片通过淡入淡出动画来更改图片? (SwiftUI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆