位于中心的水平条形图标签

时间:2018-02-02 11:57:09

标签: ios swift charts bar-chart ios-charts

我有这个简单的iOS图表实现。我正在寻找一种方法来对齐每个栏中心的标签。

到目前为止,我所做的是将标签放在每个条形图内。我坚持这一点,因为我认为没有任何方法可以实现标签的居中。

这是我完成的截图。

current accomplishment

用于设置此视图的代码片段。

func prepareHorizontalBarChart() {
        var entries1 = [BarChartDataEntry]()
        var entries2 = [BarChartDataEntry]()
        var entries3 = [BarChartDataEntry]()

        let values:[String] = ["1/22", "1/25", "1/30"]

        let bar1 = BarChartDataEntry(x: Double(0), y: Double(4), icon: nil, data: "1/22" as AnyObject)
        entries1.append(bar1)

        let bar2 = BarChartDataEntry(x: Double(1), y: Double(6))
        entries2.append(bar2)

        let bar3 = BarChartDataEntry(x: Double(2), y: Double(2))
        entries3.append(bar3)

        let set1 = BarChartDataSet(values: entries1, label: "test")
        set1.drawIconsEnabled = false

        let set2 = BarChartDataSet(values: entries2, label: "test")
        set1.drawIconsEnabled = false

        let set3 = BarChartDataSet(values: entries3, label: "test")
        set1.drawIconsEnabled = false

        set1.colors = [UIColor.purple]
        set2.colors = [UIColor.magenta]
        set3.colors = [UIColor.red]

        let data = BarChartData(dataSets: [set1, set2, set3])
        data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 10))
        data.barWidth = 0.2

        let formatter = NumberFormatter()
        formatter.numberStyle = .none
        formatter.maximumFractionDigits = 0
        formatter.multiplier = 1.0
        let defaultValueFormatter = DefaultValueFormatter(formatter: formatter)
        data.setValueFormatter(defaultValueFormatter)

        horizontalBarChart.zoomOut()
        horizontalBarChart.fitBars = true
        horizontalBarChart.data = data

        horizontalBarChart.xAxis.drawGridLinesEnabled = false // disable horizontal grid lines
//        horizontalBarChart.xAxis.enabled = false
        horizontalBarChart.chartDescription?.enabled = false
        horizontalBarChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: values)
        horizontalBarChart.xAxis.labelPosition = .bottom

        horizontalBarChart.rightAxis.enabled = false
        horizontalBarChart.leftAxis.axisMinimum = 0

        horizontalBarChart.legend.verticalAlignment = .top
        horizontalBarChart.legend.horizontalAlignment = .center

        horizontalBarChart.legend.orientation = .vertical

        horizontalBarChart.drawValueAboveBarEnabled = false
        horizontalBarChart.legend.enabled = false

        horizontalBarChart.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)

    }

1 个答案:

答案 0 :(得分:1)

  • 转到图表并查找HorizontalBarChartRender类,找到一个名为绘图值的方法,并将文本对齐的值更改为居中。

  • :搜索这两行

    1. let x = transformed[k].x + (drawBelow ? negOffset : posOffset)

      替换为

      let x = buffer.rects[k].origin.x + buffer.rects[k].size.width / 2.2

    2. if !viewPortHandler.isInBoundsTop(rect.origin.y) { break }

      注释掉这一行