Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Chart corner radius

I am trying to apply a corner radius to a horizontal 1D sectioned chart. The best I have achieved is top and bottom trailing having a corner radius. I have also tried using clip shape but I have the same results.

import SwiftUI
import Charts

let testData: [Profit] = [
    Profit(department: "Production", profit: 15000),
    Profit(department: "Marketing", profit: 8000),
    Profit(department: "Finance", profit: 10000)
]

struct ContentView: View {
    var body: some View {
        VStack {
            Chart(testData) {
                BarMark(
                    x: .value("Profit", $0.profit)
                )
                .foregroundStyle(Color.random(randomOpacity: false))
                .cornerRadius(15)
            }
            .chartLegend(.hidden)
            .chartXAxis(.hidden)
            .frame(height: 50)
            .padding(.horizontal)
        }
        .padding(100)
    }
}

struct Profit: Identifiable {
    let id = UUID()
    let department: String
    let profit: Double
}

public extension Color {
    
    static func random(randomOpacity: Bool = false) -> Color {
        Color(
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1),
            opacity: randomOpacity ? .random(in: 0...1) : 1
        )
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

horizontal 1D sectioned chart

like image 957
jat Avatar asked Oct 24 '25 05:10

jat


1 Answers

It's actually simple

Can be obtained with either

.clipShape(Capsule())

or

.clipShape(Rectangle())
.cornerRadius(15)

As modifiers to Chart.

like image 157
jat Avatar answered Oct 27 '25 02:10

jat