如何在Core Plot饼图上正确显示值

时间:2018-01-16 02:03:45

标签: ios swift3 core-plot

所以目前我有一个饼图,显示用户记录费用的每个类别所花费的金额。这是使用Core Plot。当我有2或3个类别时,图表很好,看起来像这样。

enter image description here

但是,只要我添加多个类别,视图就会失真,如下所示:

enter image description here

这是我的代码决定了这一点,而我似乎无法修复它。

func configureGraph() {
    let graph = CPTXYGraph(frame: hostView.bounds)
    hostView.hostedGraph = graph
    graph.paddingLeft = 0.0
    graph.paddingTop = 0.0
    graph.paddingRight = 0.0
    graph.paddingBottom = 0.0
    graph.axisSet = nil

    // 2 - Create text style
    let textStyle: CPTMutableTextStyle = CPTMutableTextStyle()
    textStyle.color = CPTColor.black()
    textStyle.fontName = "HelveticaNeue-Bold"
    textStyle.fontSize = 16.0
    textStyle.textAlignment = .center

    // 3 - Set graph title and text style
    graph.title = ""
    graph.titleTextStyle = textStyle
    graph.titlePlotAreaFrameAnchor = CPTRectAnchor.top
}

func configureChart() {
    var i:Float = 0
    for c in categoryTotals{
        if Int(c) != 0{
            i+=1
        }
    }
    let graph = hostView.hostedGraph!

    // 2 - Create the chart
    let pieChart = CPTPieChart()
    pieChart.delegate = self
    pieChart.dataSource = self
    pieChart.pieRadius = (min(hostView.bounds.size.width, hostView.bounds.size.height) * 0.7) / 2
    pieChart.identifier = NSString(string: graph.title!)
    pieChart.startAngle = CGFloat(M_PI_4)
    pieChart.sliceDirection = .clockwise
    pieChart.labelOffset = CGFloat(-1.8/i) * pieChart.pieRadius

    // 3 - Configure border style
    if i>1{
    let borderStyle = CPTMutableLineStyle()
    borderStyle.lineColor = CPTColor.white()
    borderStyle.lineWidth = 2.0
    pieChart.borderLineStyle = borderStyle
    }

    // 4 - Configure text style
    let textStyle = CPTMutableTextStyle()
    textStyle.color = CPTColor.white()
    textStyle.textAlignment = .center
    textStyle.fontSize = 15
    pieChart.labelTextStyle = textStyle

    // 5 - Add chart to graph
    graph.add(pieChart)
}

1 个答案:

答案 0 :(得分:1)

这不是CorePlot特有的,问题是切片可能而且确实太小而无法包含标签。

建议使用Legend,并仅在饼图内显示%。

使用传奇的好指南是: raywenderlich

向下滚动到 Legen … Wait For It… dary!

以下是Ray Wenderlich的例子

Example