🐤

swiftでpiechartメーターを作成する

2024/05/10に公開

こんな感じのpieChartっぽいメータを作成しました

import UIKit
import SwiftUI

class ViewController: UIViewController {
    @IBOutlet weak var pieChartView: UIView!
    //分母のvalue
    var targetValue: Double = 100
  //分子のvalue 70/100
    var value: Double = 70
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    private func setupViews() {
//ここでViewのsetupを呼ぶ
        setupPieChart()
    }
//pieChartのViewSetupを行う
   //MARK: - PieChartを設定するfunc
    private func setupPieChart() {
//screenSizeはpieChartViewの方でCGSizeを定義
        let pieChart = PieChart(screenSize: pieChartView.bounds.size, targetValue: targetValue, Value: value)
//SwiftUIを使用しているのでUIHostingControllerでUIkItと連携
        let chartVC = UIHostingController(rootView: pieChart)
//chartVC(UIViewControllerのインスタンス)をpieChartViewの境界に合わせている
        chartVC.view.frame = pieChartView.bounds
//pieChartViewの子ビューとしてchartVC.viewを追加している
        pieChartView.addSubview(chartVC.view)
    }

}

PieChartのビュークラス

import UIKit
import SwiftUI

@available(iOS 16.0, *)
struct PieChart: View {
    var screenSize: CGSize
    var targetValue: Double
    var Value: Double
    
    var body: some View {
        ZStack {
            Circle() // 背面のサークル
                .trim(from: 0.0, to: 1)
                .stroke(Color(red: 0.8, green: 0.8, blue: 0.8).opacity(0.1), style: StrokeStyle(lineWidth: 26, lineCap: .butt))
                .frame(width: screenSize.width, height: screenSize.height)
                .rotationEffect(.degrees(0))
                .shadow(color: .gray.opacity(0.3), radius: 1, x: 1, y:1)
            
            Circle() // 緑のサークル
                .trim(from: 0.0, to: min(CGFloat(Value) / CGFloat(targetValue), 1.0))
                .stroke(Color.green, style: StrokeStyle(lineWidth: 26, lineCap: .butt))
                .frame(width: screenSize.width, height: screenSize.height)
                .rotationEffect(.degrees(0))
                .shadow(color: .gray, radius: 1, x: 1, y: 1)
        }
        .onAppear {
            let ratio = CGFloat(Value) / CGFloat(targetValue)
        }
    }
}

こちらを参考にしました
参考元
https://developer.apple.com/documentation/charts/chart/
https://stackoverflow.com/questions/78137349/half-donut-chart-using-swiftui-sectormark

Discussion