Skip to content
Pie Chart preview
Rendered from the SwiftUI source on this page.

Pie Chart

From syxUI — written for both platforms, not translated between them.

A pie chart with a side legend and percentages.

Charts · SwiftUI · iOS 17

  • charts
  • swiftui

The actual source

PieChart2.swift
// Pie Chart · syxUI · https://syxui.dev/components/chart2-pie
// Free in any project. Keep this line and credit syxUI where a person can read it.

import SwiftUI

extension View {
    func formaCard(_ pad: CGFloat = 18) -> some View {
        self.padding(pad)
            .background(Color(.systemBackground), in: RoundedRectangle(cornerRadius: 20, style: .continuous))
            .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).stroke(Color.primary.opacity(0.06), lineWidth: 1))
            .shadow(color: .black.opacity(0.05), radius: 14, x: 0, y: 6)
    }
}

// Pie chart with legend
struct PieChart2: View {
    let slices: [(Double, Color, String)] = [(0.4, Color(red: 0.0, green: 0.47, blue: 1.0), "Direct"), (0.28, Color(red: 0.55, green: 0.40, blue: 0.90), "Social"), (0.2, Color(red: 0.16, green: 0.66, blue: 0.40), "Search"), (0.12, Color(red: 0.98, green: 0.55, blue: 0.10), "Email")]
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("Traffic sources").font(.system(size: 15, weight: .semibold))
            HStack(spacing: 18) {
                Canvas { ctx, size in
                    let c = CGPoint(x: size.width / 2, y: size.height / 2); let r = min(size.width, size.height) / 2
                    var start = -90.0
                    for s in slices {
                        let sweep = s.0 * 360
                        var path = Path(); path.move(to: c)
                        path.addArc(center: c, radius: r, startAngle: .degrees(start), endAngle: .degrees(start + sweep), clockwise: false)
                        path.closeSubpath()
                        ctx.fill(path, with: .color(s.1)); start += sweep
                    }
                }.frame(width: 110, height: 110)
                VStack(alignment: .leading, spacing: 8) {
                    ForEach(Array(slices.enumerated()), id: \.offset) { _, s in
                        HStack(spacing: 8) { RoundedRectangle(cornerRadius: 3).fill(s.1).frame(width: 10, height: 10); Text(s.2).font(.system(size: 13)); Spacer(); Text("\(Int(s.0 * 100))%").font(.system(size: 13, weight: .semibold)) }
                    }
                }
            }
        }.formaCard().frame(width: 320)
    }
}
iOS 17 · No dependencies

Dependencies

SwiftUI
No external dependencies

Requires iOS 17