SwiftUI学习笔记之Animations(二)

Stepper也可以动画
先定义一个缩放尺寸的变量

@State private var sizeAmount : CGFloat = 1

然后

VStack{
            Stepper("调整图形大小",
                    value: $sizeAmount
                .animation(Animation
                    .easeIn(duration: 2)
                    .repeatCount(3)
                )
                ,in:1...2 ,step: 0.1)
            Spacer()
            Circle()
                .foregroundColor(Color.red)
                .frame(width: 200, height: 200, alignment: .center)
                .scaleEffect(sizeAmount,anchor: .center)
            Spacer()
                
        }

Stepper的范围设定为1到2,每按下一次则增加0.1,当sizeAmount变化时,采用easeIn方式,并且重复三次。当调整Stepper时,下方红色圆球则相应变化。
在这里插入图片描述
在这里插入图片描述
SwiftUI的动画可以应用到很多方面。

弹性动画
interpolatingSpring

当按键被按下式,旋转,并且进行弹性动画旋转

@State private var animationAmount = 0.0
    
    var body: some View {
        Button("点我") {
            withAnimation(
                Animation.interpolatingSpring(stiffness: 5, damping: 1)
            ){
                self.animationAmount += 360
            }
            
        }
        .padding(50)
        .background(Color.red)
        .foregroundColor(.white)
        .clipShape(Circle())
        .rotation3DEffect(.degrees(animationAmount), axis: (x: 0, y: 1, z: 0))
    }
}

旋转方式设为3d旋转,并且以Y轴为旋转轴,可以修改为其它两个轴,但是不能同时都设为1。
除了配置参数stiffness于damping外,interpolationSpring的完整初始化函数为

static func interpolatingSpring(mass: Double = 1.0, stiffness: Double, damping: Double, initialVelocity: Double = 0.0) -> Animation

还能初始化速度,规模等等。在这里插入图片描述

在这里插入图片描述

手势➕动画

@State private var dragAmount = CGSize.zero
var body: some View {
        VStack{
            LinearGradient(gradient: Gradient(colors: [.orange,.green]), startPoint: .topLeading, endPoint: .bottomLeading)
                .frame(width: 300, height: 200, alignment: .center)
                .clipShape(RoundedRectangle(cornerRadius: 10))
                .offset(animationAmount)
            .gesture(
                DragGesture()
                    .onChanged{
                        offset in
                        withAnimation(Animation.easeOut(duration: 1)){
                            self.animationAmount = offset.translation
                        }
                    
                }
                    .onEnded{
                        _ in
                        withAnimation(Animation.interpolatingSpring(stiffness: 10, damping: 5)){
                            self.animationAmount = CGSize.zero
                        }
                }
            
            )
        }
    }

大小为300*200的桔色绿色渐变方块,当拖动时稍微延迟移动到鼠标位置,而放开鼠标后,弹性动画方式回到初始位置。
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jackwsd/article/details/107514566