代码之家  ›  专栏  ›  技术社区  ›  az2902

matchedGeometryEffect无法平滑设置动画

  •  0
  • az2902  · 技术社区  · 5 年前

    我想做一个简单的 matchedGeometryEffect 但它不起作用。我有一个简单的答案 Image 它有一个固定的框架,我想把它设置成动画 形象 这占据了整个屏幕。这就是它现在的样子,正如你所看到的,它不会平稳过渡:

    enter image description here

    这是我的代码:

    struct ContentView: View {
        @State private var enlarged = false
        @Namespace private var animation
        
        var body: some View {
            ZStack {
                if (enlarged) {
                    Image("dunes")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .matchedGeometryEffect(id: "image", in: animation)
                        .ignoresSafeArea(.all, edges: .all)
                } else {
                    Image("dunes")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .matchedGeometryEffect(id: "image", in: animation)
                        .frame(width: 300, height: 225)
    
                }
            }
            .onTapGesture {
                withAnimation {
                    enlarged.toggle()
                }
            }
        }
    }
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   Roland Lariotte    5 年前

    使 matchedGeometryEffect 动画制作流畅,你几乎没有什么规则可以遵循。你必须在电影结束后声明拍摄 匹配几何效应 。动画必须放在每个图像的末尾,而不是放在图像中 .tapGesture .

    以下是经过修改的代码:

    struct ContentView: View {
    
      @State private var enlarged = false
      @Namespace private var namespace
    
      var body: some View {
        ZStack {
          if enlarged {
            Image("dunes")
              .resizable()
              .matchedGeometryEffect(id: "image", in: namespace)
              .aspectRatio(contentMode: .fill)
              .ignoresSafeArea(.all, edges: .all)
              .animation(.easeInOut)
          }
          else {
            Image("dunes")
              .resizable()
              .matchedGeometryEffect(id: "image", in: namespace)
              .aspectRatio(contentMode: .fill)
              .frame(width: 300, height: 225)
              .animation(.easeInOut)
    
          }
        }
        .onTapGesture { enlarged.toggle() }
      }
    }