如何解决SwiftUI CPU 对实时 ForEach 视图更新的高使用率 (macOS)
所以我有一个视图,我正在计算音频文件的振幅,然后将其传递给视图以绘制它并实时更改。问题是图表在几秒钟后变得如此滞后,cpu 使用率最大化,几乎所有东西都冻结了。 有没有办法在 SwiftUI macOS 中使用 GPU 而不是 cpu 来渲染视图?
我正在更新 dispatchQueue.main.async
中的振幅值并发送 NSNotification
。
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 举报,一经查实,本站将立刻删除。