我想改变的是,标签不是在那个地方结束,而是从那个地方开始,这样就可以看到整个文本。我使用的代码:
barChart.axisLeft.isEnabled = false
barChart.setTouchEnabled(false)
barChart.isDragEnabled = false
barChart.description = null
barChart.xAxis.setDrawGridLines(false)
barChart.xAxis.setCenterAxisLabels(true)
barChart.xAxis.valueFormatter = IndexAxisValueFormatter(nameArray)
barChart.xAxis.position = XAxis.XAxisPosition.BOTTOM_INSIDE
barChart.xAxis.textColor = Color.WHITE
barChart.axisRight.textColor = Color.WHITE
barChart.legend.textColor = Color.WHITE
提前致谢:)
条形图上的轴标签可能很难正确定位,因此对于类似的东西,通常更容易使用数据集值的自定义渲染器。为此,您可以创建一个自定义渲染器,从
BarEntry
数据字段中读取所需的标签,并将其绘制在相对于条形位置的所需位置。
HorizontalBarChartRenderer
的简化副本,它覆盖了 drawValues
方法。
class MyRenderer(
chart: HorizontalBarChart
) : HorizontalBarChartRenderer(chart, chart.animator, chart.viewPortHandler) {
override fun drawValues(c: Canvas?) {
val dataSets = mChart.barData.dataSets
val valueOffsetPlus = Utils.convertDpToPixel(5f)
dataSets.forEachIndexed { i, ds ->
applyValueTextStyle(ds)
val buffer = mBarBuffers[i]
val maxJ = ceil(buffer.buffer.size*mAnimator.phaseX).toInt()
for(j in 0 until maxJ step 4) {
if( !mViewPortHandler.isInBoundsTop(buffer.buffer[j+1]))
break
if( !mViewPortHandler.isInBoundsX(buffer.buffer[j]))
continue
if( !mViewPortHandler.isInBoundsBottom(buffer.buffer[j+1]))
continue
// Read the label from the BarEntry data field
val entry = ds.getEntryForIndex(j / 4)
val formattedValue = (entry.data as? String).orEmpty()
// Modify the x, y position here to control where the
// text is. The "buffer" array gives the positions of
// the current bar (in pixels from top left corner)
drawValue(c,
formattedValue,
buffer.buffer[j] + valueOffsetPlus,
buffer.buffer[j+1] + ds.valueTextSize,
ds.getValueTextColor(j / 2));
}
}
}
}
定义自定义渲染器后,将其添加到带有标签列表的图表中,并关闭常规轴标签,如下所示:
// set the custom renderer for the chart
barChart.renderer = MyRenderer(barChart)
// turn off labels on x axis
barChart.xAxis.setDrawLabels(false)
对于这个例子,我使用以下数据集
val entries1 = listOf(BarEntry(0f,3f,"Lorem"))
val dataset1 = BarDataSet(entries1, "Foo").apply { color = Color.GREEN }
val entries2 = listOf(
BarEntry(1f,4f,"Ipsum"),
BarEntry(2f,5f,"Dolorum")
)
val dataset2 = BarDataSet(entries2, "Bar").apply { color = Color.LTGRAY }
val entries3 = listOf(BarEntry(3f,6f,"Pescotum"))
val dataset3 = BarDataSet(entries3, "Baz").apply { color = Color.CYAN }
val sets = listOf(dataset1, dataset2, dataset3)
sets.forEach { it.valueTextSize = 12f }
barChart.data = BarData(sets)
您还可以查看 this solution 的版本(在 Java 中)将标签绘制在条形之外。