首页 > 解决方案 > matchedGeometryEffect 动画不流畅

问题描述

我正在尝试做一个简单matchedGeometryEffect的事情,但它不起作用。我有一个简单Image的框架,它有一个固定的框架,我想将它设置为一个Image占据整个屏幕的动画。这就是它现在的样子,正如你所看到的,它并没有顺利过渡:

在此处输入图像描述

这是我的代码:

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()
            }
        }
    }
}

标签: iosswiftswiftui

解决方案


为了使matchedGeometryEffect动画顺利进行,您几乎没有遵循的规则。您必须在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() }
  }
}

推荐阅读