SwiftUI CPU 对实时 ForEach 视图更新的高使用率 (macOS)

问题描述

所以我有一个视图,我正在计算音频文件的振幅,然后将其传递给视图以绘制它并实时更改。问题是图表在几秒钟后变得如此滞后,cpu 使用率最大化,几乎所有东西都冻结了。 有没有办法在 SwiftUI macOS 中使用 GPU 而不是 cpu 来渲染视图?

我正在更新 dispatchQueue.main.async 中的振幅值并发送 NSNotification

SwiftUI Graph Real Time Updating

这是我想显示图表时调用文件

struct TimeDomain: View {
    
    @Binding var manager: AVManager
    @State var pub = DSPNotification().publisherPath()
    @State var amps =  [Double]()
    
    var body: some View {

        AmplitudeVisualizer(amplitudes: $amps).frame(height: 300)
            .onReceive(pub) { (output) in
                self.amps = manager.amplitudes
            }
            .onAppear {
                self.amps = manager.amplitudes
            }
            .drawingGroup()
    }
}

AmplitudeVisualizer.swift

文件
struct AmplitudeVisualizer: View {
    
    @Binding var amplitudes: [Double]
    
    var body: some View {
        HStack(spacing: 0.0){
            ForEach(0..<self.amplitudes.count,id: \.self) { number in
                VerticalBar(amplitude: self.$amplitudes[number])
            }
            .drawingGroup()
        }
    }
    
}

VerticalBar.swift

/// Single bar of Amplitude Visualizer
struct VerticalBar: View {
    
    @Binding var amplitude: Double
    
        var body: some View {
            GeometryReader
                { geometry in
                ZStack(alignment: .bottom){
    
                    // Colored rectangle in back of ZStack
                    Rectangle()
                        .fill(LinearGradient(gradient: Gradient(colors: [.red,.yellow,.green]),startPoint: .top,endPoint: .center))
    
                        // blue/purple bar style - try switching this out with the .fill statement above
                        //.fill(LinearGradient(gradient: Gradient(colors: [Color.init(red: 0.0,green: 1.0,blue: 1.0),.blue,.purple]),endPoint: .bottom))
    
                    // Dynamic black mask padded from bottom in relation to the amplitude
                    Rectangle()
                        .fill(Color.black)
                        .mask(Rectangle().padding(.bottom,geometry.size.height * CGFloat(self.amplitude)))
                        .animation(.eaSEOut(duration: 0.05))
    
                    // White bar with slower animation for floating effect
                    Rectangle()
                        .fill(Color.white)
                        .frame(height: geometry.size.height * 0.005)
                        .offset(x: 0.0,y: -geometry.size.height * CGFloat(self.amplitude) - geometry.size.height * 0.02)
                        .animation(.eaSEOut(duration: 0.6))
    
                }
                .padding(geometry.size.width * 0.1)
                .border(Color.black,width: geometry.size.width * 0.1)
            }.drawingGroup()
        }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)