0

I am practising matchedGeometryEffect.

struct ContentView: View {
    @Namespace var tem
    @State var isTemp: Bool = true
        
    var body: some View{
        ZStack{
            if isTemp{
                Circle()
                    .matchedGeometryEffect(id: "haha", in: tem, anchor: .center)
                    .foregroundColor(.green)
                    .frame(width: 200, height: 200)
            }else{
                Rectangle()
                    .matchedGeometryEffect(id: "haha", in: tem, anchor: .center)
                    .foregroundColor(.blue).opacity(0.4)
                    .frame(width: 400, height: 600)
            }
            
            Button {
                withAnimation(.linear(duration: 5)){
                    isTemp = false
                }
            } label: {
                Text("switch")
            }
        }
    }
}

If I set anchor to top, it works well with the tops of both shapes remaining alignment. When I set anchor to center, I expect both shapes should stay at the center point of screen and extend around. However, only the rectangle stays still as expected, while the circle descends like bottom anchor effect. What's more, if I set anchor to bottom, the circle descends more quickly. Is it a normal behavior? Do I miss anything?

test1229
  • 125
  • 9

1 Answers1

0

Anchor does not mean alignment in the surrounding View, but which anchor point of your view swiftui uses to animate around. It helped me to play around with the more extensive version of matchedGeometryEffect.

Circle()
.matchedGeometryEffect(id: "haha", in: tem, properties: .position, anchor: .bottom, isSource: false)

Warning: isSourceis default true, so put in one as false.

Now when only the position is animated, you can quickly see, that the anchor of the circle is animated on top of the anchor of the Rectangle.

Hope that helps

Celina
  • 513
  • 4
  • 21