1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【MPAndroidChart】棒グラフの外枠の色を複数指定(renderer)

Last updated at Posted at 2022-07-07

概要

MPAndroidChartでのパラメータでの設定以上のことを行いたい場合。
棒グラフの色はsetColors()を使用してリストで設定できるが、外枠はbarBorderWidthで指定するので、リストで設定できない。

方法

rendererを使用。

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.github.mikephil.charting.charts.BarChart
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/chart"
	android:layout_width="match_parent"
	android:layout_height="match_parent"/>
MainActivity.kt
val value = listOf(
	BarEntry(0f, floatArrayOf(5f, 2f)),
	BarEntry(1f, floatArrayOf(6f, 3f)),
	BarEntry(2f, floatArrayOf(8f, 6f)),
	BarEntry(3f, floatArrayOf(12f, 9f)),
	BarEntry(4f, floatArrayOf(15f, 14f))
)

val set = BarDataSet(value, "")
set.setColors(getColor(R.color.bar1), getColor(R.color.bar2))
set.barBorderWidth = 2f
//単色の指定のみ
//set.barBorderColor = getColor(R.color.border1)
binding.chart.data = BarData(set)

//rendererを用いて外枠の色を複数指定。
binding.chart.renderer = object : BarChartRenderer(binding.chart, binding.chart.animator, binding.chart.viewPortHandler) {
	override fun drawDataSet(c: Canvas, dataSet: IBarDataSet, index: Int) {
		val buffer = mBarBuffers[index]
		buffer.setPhases(mAnimator.phaseX, mAnimator.phaseY)
		buffer.setDataSet(index)
		buffer.setInverted(mChart.isInverted(dataSet.axisDependency))
		buffer.setBarWidth(mChart.barData.barWidth)
		buffer.feed(dataSet)
		mChart.getTransformer(dataSet.axisDependency).pointValuesToPixel(buffer.buffer)

		val strokeWidth = Utils.convertDpToPixel(dataSet.barBorderWidth)
		mBarBorderPaint.color = dataSet.barBorderColor
		mBarBorderPaint.strokeWidth = strokeWidth

		var j = 0
		while (j < buffer.size()) {
			if (!mViewPortHandler.isInBoundsTop(buffer.buffer[j + 3])) break
			if (!mViewPortHandler.isInBoundsBottom(buffer.buffer[j + 1])) {
				j += 4
				continue
			}
			mRenderPaint.color = dataSet.getColor(j / 4)
			mBarBorderPaint.color = getColor(if (j / 4 % 2 == 0) R.color.border1 else R.color.border2)
			c.drawRect(
				buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
				buffer.buffer[j + 3], mRenderPaint
			)
			c.drawRect(
				buffer.buffer[j] + strokeWidth / 2, buffer.buffer[j + 1] + strokeWidth / 2, buffer.buffer[j + 2] - strokeWidth / 2,
				buffer.buffer[j + 3] - strokeWidth / 2, mBarBorderPaint
			)
			j += 4
		}
	}
}

binding.chart.invalidate()

関連記事

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?