代码之家  ›  专栏  ›  技术社区  ›  swiftPunk Alexander

如何从matchedGeometryEffect中移除/控制渐变效果?

  •  0
  • swiftPunk Alexander  · 技术社区  · 4 年前

    我有一个测试代码来显示这个问题,当我使用matchedGeometryEffect时,matchedGeometryEffect会在渲染结果中添加一个未修剪的渐变效果,所以我喜欢删除甚至控制它。当我将视图的颜色从一种颜色更改为另一种颜色时,这可能是一件好事,但在我的情况下,这并不好,因为颜色一直是黑色的。

    struct ContentView: View {
        
        @Namespace var animationNamespaceon
        @State private var start: Bool = Bool()
        
        var body: some View {
            
            VStack {
                
                Spacer()
                
                circle
                
                Spacer()
                
                Button("update") { start.toggle() }
                
            }
            .animation(Animation.linear(duration: 3), value: start)
    
        }
        
       @ViewBuilder var circle: some View {
            if start {
                
                Circle()
                    .foregroundColor(Color.black)
                    .matchedGeometryEffect(id: "Circle", in: animationNamespaceon)
                    .frame(width: 300, height: 300)
    
    
            }
            else {
                Circle()
                    .foregroundColor(Color.black)
                    .matchedGeometryEffect(id: "Circle", in: animationNamespaceon)
                    .frame(width: 50, height: 50)
                    
            }
        }
    }
    
    0 回复  |  直到 4 年前
        1
  •  8
  •   Martijn Pieters    4 年前

    这是默认的效果 .transition(.opacity) 当视图被从视图层次结构中移除(插入到)时应用该方法。

    我想你需要线性比例转换,比如

        if start {
            Circle()
                .foregroundColor(Color.black)
                .matchedGeometryEffect(id: "Circle", in: animationNamespaceon)
                .transition(.scale(scale: 1))
                .frame(width: 300, height: 300)
        }
        else {
            Circle()
                .foregroundColor(Color.black)
                .matchedGeometryEffect(id: "Circle", in: animationNamespaceon)
                .transition(.scale(scale: 1))
                .frame(width: 50, height: 50)
        }
    

    使用Xcode 13/iOS 15进行测试