繁体   English   中英

SwiftUI | 为这个路径形状设置动画

[英]SwiftUI | Animate This Path Shape

我有以下情况:

我想用自定义动画翻转这个形状。 我不知道如何恰当地描述它。

每当我点击箭头时,它应该变成另一个箭头。 无需翻转、旋转等,只需简单地变换即可。

如果不够准确,欢迎评论!

演示代码

struct ContentView: View {
    
    @State private var change = false
    
    private let arrowWidth: CGFloat = 80
    
    
    var body: some View {
        Path { path in
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: arrowWidth/2, y: change ? -20 : 20))
            path.move(to: CGPoint(x: arrowWidth/2, y: change ? -20 : 20))
            path.addLine(to: CGPoint(x: arrowWidth, y: 0))
        }
        .stroke(style: StrokeStyle(lineWidth: 12, lineCap: .round))
        .frame(width: arrowWidth)
        .foregroundColor(.green)
        .animation(.default)
        .onTapGesture { change.toggle() }
        .padding(.top, 300)
    }
}

正如你现在看到的,它没有动画。 我不知道该怎么做。

任何帮助深表感谢。 谢谢!

注意:我不能用两个圆角矩形+简单地旋转来做到这一点,因为我有一个不透明动画,这使得重叠可见。

这是可能的方法 - 将路径移动到自定义形状并将更改的参数作为动画属性。

更新:使用 Xcode 13.3 / iOS 15.4 重新测试

演示

struct MyArrow: Shape {
    var width: CGFloat
    var offset: CGFloat
    
    var animatableData: CGFloat {
        get { offset }
        set { offset = newValue }
    }
    
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: width/2, y: offset))
            path.move(to: CGPoint(x: width/2, y: offset))
            path.addLine(to: CGPoint(x: width, y: 0))
        }
    }
}

struct ContentView: View {
    
    @State private var change = false
    
    private let arrowWidth: CGFloat = 80
    
    
    var body: some View {
        MyArrow(width: arrowWidth, offset: change ? -20 : 20)
        .stroke(style: StrokeStyle(lineWidth: 12, lineCap: .round))
        .frame(width: arrowWidth)
        .foregroundColor(.green)
        .contentShape(Rectangle())
        .onTapGesture { withAnimation { change.toggle() } }
        .onTapGesture { change.toggle() }
        .padding(.top, 300)
    }
}

备份

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM