swift 快速图表:如何在折线图中为突出显示的区域添加阴影?

t8e9dugd  于 2022-12-22  发布在  Swift
关注(0)|答案(2)|浏览(132)


下面的代码在我想高亮显示的区域的顶部和底部绘制了一个RuleMark,但是,我想把这个区域涂成灰色来显示正常范围,而不是两条线。我该怎么做呢?

import SwiftUI
import Charts

struct ContentView: View {
    
    struct StepCount: Identifiable {
        let id = UUID()
        let weekday: Date
        let steps: Int
        
        init(day: String, steps: Int) {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyyMMdd"
            
            self.weekday = formatter.date(from: day) ?? Date.distantPast
            self.steps = steps
        }
    }
    
    let currentWeek: [StepCount] = [
        StepCount(day: "20220717", steps: 4200),
        StepCount(day: "20220718", steps: 15000),
        StepCount(day: "20220719", steps: 2800),
        StepCount(day: "20220720", steps: 10800),
        StepCount(day: "20220721", steps: 12370),
        StepCount(day: "20220722", steps: 9500),
        StepCount(day: "20220723", steps: 3700)
    ]
    
    var body: some View {
        VStack {
            Chart {
                ForEach(currentWeek) {
                    LineMark(
                        x: .value("Week Day", $0.weekday, unit: .day),
                        y: .value("Step Count", $0.steps)
                    )
                }
                RuleMark(y: .value("Max of Range", 10000))
                    .foregroundStyle(.red)
                RuleMark(y: .value("Min of Range", 6000))
                    .foregroundStyle(.red)
            }
        }
        .frame(height: 200)
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}[![enter image description here][1]][1]
tquggr8v

tquggr8v1#

如果区域应跨越整个图表(尤其是日期值),则可以按如下方式使用RectangeMark

Chart {
                RectangleMark(
                    xStart: nil,
                    xEnd: nil,
                    yStart: .value("Step Count", 6000),
                    yEnd: .value("Step Count", 10000)
                )
                .foregroundStyle(.gray)

                ForEach(currentWeek) {
                    
                    LineMark(
                        x: .value("Week Day", $0.weekday, unit: .day),
                        y: .value("Step Count", $0.steps)
                    )
                }
            }
oug3syen

oug3syen2#

您可以使用AreaMarkRectangleMark。以下是使用AreaMark的示例:

Chart {
                ForEach(currentWeek) {
                    AreaMark(x: .value("Week Day", $0.weekday, unit: .day),
                             yStart: .value("Min of Range", 6000),
                             yEnd: .value("Max of Range", 10000))
                    .foregroundStyle(.gray)

                    LineMark(
                        x: .value("Week Day", $0.weekday, unit: .day),
                        y: .value("Step Count", $0.steps)
                    )
                }
            }

相关问题