简体   繁体   English

Swift 图表 (iOS 16) 饼图/甜甜圈图

[英]Swift Charts (iOS 16) Pie / Donut Chart

is it possible to create a Pie / Donut chart using Apple's new Swift Charts framework?是否可以使用 Apple 的新 Swift 图表框架创建饼图/甜甜圈图?

there are images of a pie chart shown in the WWDC videos. WWDC 视频中显示了饼图的图像。 Any help or code sample on how to create the pie chart will be much appreciated.任何有关如何创建饼图的帮助或代码示例将不胜感激。

Thanks谢谢

Swift Charts does not (yet?) support polar geometry, which is what you need to build pie charts. Swift 图表不(还?)支持极坐标几何,这是构建饼图所需的。

I would recommend using a Canvas and drawing the information yourself, something like this:我建议使用Canvas并自己绘制信息,如下所示:

struct Pie: View {

    @State var slices: [(Double, Color)]

    var body: some View {
        Canvas { context, size in
            let total = slices.reduce(0) { $0 + $1.0 }
            context.translateBy(x: size.width * 0.5, y: size.height * 0.5)
            var pieContext = context
            pieContext.rotate(by: .degrees(-90))
            let radius = min(size.width, size.height) * 0.48
            var startAngle = Angle.zero
            for (value, color) in slices {
                let angle = Angle(degrees: 360 * (value / total))
                let endAngle = startAngle + angle
                let path = Path { p in
                    p.move(to: .zero)
                    p.addArc(center: .zero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
                    p.closeSubpath()
                }
                pieContext.fill(path, with: .color(color))

                startAngle = endAngle
            }
        }
        .aspectRatio(1, contentMode: .fit)
    }
}

struct Pie_Previews: PreviewProvider {
    static var previews: some View {
        Pie(slices: [
            (2, .red),
            (3, .orange),
            (4, .yellow),
            (1, .green),
            (5, .blue),
            (4, .indigo),
            (2, .purple)
        ])
    }
}

在此处输入图像描述

To make a donut chart, clip the canvas as the first thing you do in the rendering closure:要制作圆环图,请将 canvas 剪辑为您在渲染闭包中执行的第一件事:

let donut = Path { p in
    p.addEllipse(in: CGRect(origin: .zero, size: size))
    p.addEllipse(in: CGRect(x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5))
}
context.clip(to: donut, style: .init(eoFill: true))

在此处输入图像描述

Yes it is possible in Apple's new swift UI by using charts , swiftUI and foundation libraries是的,可以在 Apple 的新 swift UI 中使用图表swiftUI 和基础

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM