You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何阻止Shape重复计算已生成的路径?

SwiftUI Shape 重复计算性能问题

我实现了一个仅生成圆形的简单Shape,该Shape无需接收任何参数即可输出结果,但它仍会重复调用路径计算函数。调整窗口大小或点击背景等与Shape输入无关的操作,都会触发重复计算,若路径复杂将造成大量性能损耗。

相关代码

struct ContentView: View {
    var body: some View {
        
        VStack {
            
            MyShape()
                .stroke(lineWidth: 2.0)
                .background(Color.blue)
            
        }
        .frame(width: 250.0, height: 250.0)
        .padding()
    }
}

var callCount: Int = 0

struct MyShape: Shape {
    func path(in rect: CGRect) -> Path {
        
        callCount += 1
        
        print("MyShape Called =", callCount)
        
        return Path { path in
            
            path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width/2.0, startAngle: Angle(degrees: 0.0), endAngle: Angle(degrees: 360.0), clockwise: true)

        }
    }
}

演示效果

演示动图

内容的提问来源于stack exchange,提问作者swiftPunk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:05:15