1
0

More than 1 year has passed since last update.

【MPAndroidChart】グラフ外の余白を無くす

Last updated at Posted at 2022-07-08

概要

グラフ外の余白を無くす。

余白あり 余白なし

setViewPortOffsets(0f, 0f, 0f, 0f)で余白が無くならないことがあったので、原因と対処法を記述。

原因

setViewPortOffsetsの定義を見ると、別スレッドでoffsetをセットしている。そのため、表示タイミングによってはoffsetの反映がされないことがあった。

    public void setViewPortOffsets(final float left, final float top,
                                   final float right, final float bottom) {

        mCustomViewPortEnabled = true;
        post(new Runnable() {

            @Override
            public void run() {

                mViewPortHandler.restrainViewPort(left, top, right, bottom);
                prepareOffsetMatrix();
                prepareValuePxMatrix();
            }
        });
    }

対処法1

invalidateの処理を遅らせる。

レイアウト

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, 2f),
	BarEntry(1f, 3f),
	BarEntry(2f, 9f),
	BarEntry(3f, 7f),
	BarEntry(4f, 5f)
)
binding.chart.data = BarData(BarDataSet(value, ""))

binding.chart.setViewPortOffsets(0f, 0f, 0f, 0f)
Handler(Looper.getMainLooper()).postDelayed({ binding.chart.invalidate() }, 100)

対処法2

グラフの外側にあるビューを削除し、minOffsetを0にする。HorizontalBarChartの場合、xAxis.positionTOP_INSIDEBOTTOM_INSIDEを指定しないと余白ができた。
対処法1よりも安全。

レイアウト

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, 2f),
	BarEntry(1f, 3f),
	BarEntry(2f, 9f),
	BarEntry(3f, 7f),
	BarEntry(4f, 5f)
)
binding.chart.data = BarData(BarDataSet(value, ""))

//凡例の削除
binding.chart.legend.isEnabled = false

//x軸の数値削除
binding.chart.xAxis.setDrawLabels(false)

//HorizontalBarChartのみ必要
binding.chart.xAxis.position = XAxis.XAxisPosition.BOTTOM_INSIDE

//y軸の数値削除
binding.chart.axisLeft.setDrawLabels(false)
binding.chart.axisRight.setDrawLabels(false)

//オフセットを0にする
binding.chart.minOffset = 0f

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