如何做一个简单的缩放动画,为什么这不起作用? [英] how to do a simple scaling animation and why isn't this working?

查看:33
本文介绍了如何做一个简单的缩放动画,为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在stackoverflow中读到我只能将动画与延迟连接起来,所以我在这里尝试了这个,它只是缩小然后再次缩放圆圈.不幸的是,收缩不起作用!?如果我注释掉不断增长、缩小的作品...

i just read in stackoverflow i can only concatenate animation with delay, so i tried this here which simply shrinks and then scales the circle again. unfortunately the shrinking doesn't work!? if i comment out the growing, shrinking works...

struct ContentView: View {
    
    @State var scaleImage : CGFloat = 1
    
    var body: some View {
        VStack {
            Button(action: {
                withAnimation(Animation.easeInOut(duration: 1)) {
                    self.scaleImage = 0.01
                }
                
                withAnimation(Animation.easeInOut(duration: 1).delay(1.0)) {
                    self.scaleImage = 1
                }
            }) {
                Text ("Start animation")
            }
            Image(systemName: "circle.fill")
                .scaleEffect(scaleImage)
        }
    }
}

推荐答案

这里是可能的方法(基于 AnimatableModifier).实际上,它演示了如何检测当前动画结束并执行某些操作 - 在这种情况下,对于您的缩放场景,只需启动反转即可.

Here is possible approach (based on AnimatableModifier). Actually it demonstrates how current animation end can be detected, and performed something - in this case, for your scaling scenario, just initiate reversing.

使用 Xcode 11.4/iOS 13.4 测试

Tested with Xcode 11.4 / iOS 13.4

简化&修改了你的例子

Simplified & modified your example

struct TestReversingScaleAnimation: View {

    @State var scaleImage : CGFloat = 1

    var body: some View {
        VStack {
            Button("Start animation") {
                self.scaleImage = 0.01       // initiate animation
            }

            Image(systemName: "circle.fill")
                .modifier(ReversingScale(to: scaleImage) {
                    self.scaleImage = 1      // reverse set
                })
                .animation(.default)         // now can be implicit
        }
    }
}

实际上,这里的表演者...重要评论内嵌.

Actually, show-maker here... important comments inline.

struct ReversingScale: AnimatableModifier {
    var value: CGFloat

    private var target: CGFloat
    private var onEnded: () -> ()

    init(to value: CGFloat, onEnded: @escaping () -> () = {}) {
        self.target = value
        self.value = value
        self.onEnded = onEnded // << callback
    }

    var animatableData: CGFloat {
        get { value }
        set { value = newValue
            // newValue here is interpolating by engine, so changing
            // from previous to initially set, so when they got equal
            // animation ended
            if newValue == target {
                onEnded()
            }
        }
    }

    func body(content: Content) -> some View {
        content.scaleEffect(value)
    }
}

这篇关于如何做一个简单的缩放动画,为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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