프로그래밍 언어/Java

[Android java] Mpchart specific Xlabel custom color

happy_life 2022. 2. 23. 18:10

Mpchart  specific Xlabel custom color

mpchart의 특정 x라벨의 색을 커스텀하는 방법에 대해 알아보겠습니다.

 

 

ColoredLabelXAxisRenderer 클래스를 새로 만들어줍니다.

 

package "yourPackageName";

import android.graphics.Canvas;

import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.renderer.XAxisRenderer;
import com.github.mikephil.charting.utils.MPPointF;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.Collections;
import java.util.List;

public class ColoredLabelXAxisRenderer extends XAxisRenderer {
    List<Integer> labelColors;

    public ColoredLabelXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) {
        super(viewPortHandler, xAxis, trans);
        labelColors = Collections.EMPTY_LIST;
    }

    public ColoredLabelXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans, List<Integer> colors) {
        super(viewPortHandler, xAxis, trans);
        this.labelColors = colors;
    }

    @Override
    protected void drawLabels(Canvas c, float pos, MPPointF anchor) {
        final float labelRotationAngleDegrees = mXAxis.getLabelRotationAngle();
        boolean centeringEnabled = mXAxis.isCenterAxisLabelsEnabled();

        float[] positions = new float[mXAxis.mEntryCount * 2];

        for (int i = 0; i < positions.length; i += 2) {

            // only fill x values
            if (centeringEnabled) {
                positions[i] = mXAxis.mCenteredEntries[i / 2];
            } else {
                positions[i] = mXAxis.mEntries[i / 2];
            }
        }

        mTrans.pointValuesToPixel(positions);

        for (int i = 0; i < positions.length; i += 2) {

            float x = positions[i];

            if (mViewPortHandler.isInBoundsX(x)) {
                String label = mXAxis.getValueFormatter().getFormattedValue(mXAxis.mEntries[i / 2], mXAxis);

                int color = getColorForXValue((int)mXAxis.mEntries[i / 2]); //added

                mAxisLabelPaint.setColor(color);

                if (mXAxis.isAvoidFirstLastClippingEnabled()) {

                    // avoid clipping of the last
                    if (i == mXAxis.mEntryCount - 1 && mXAxis.mEntryCount > 1) {
                        float width = com.github.mikephil.charting.utils.Utils.calcTextWidth(mAxisLabelPaint,label);

                        if (width > mViewPortHandler.offsetRight() * 2
                                && x + width > mViewPortHandler.getChartWidth())
                            x -= width / 2;

                        // avoid clipping of the first
                    } else if (i == 0) {

                        float width = com.github.mikephil.charting.utils.Utils.calcTextWidth(mAxisLabelPaint, label);
                        x += width / 2;
                    }
                }

                drawLabel(c, label, x, pos, anchor, labelRotationAngleDegrees);
            }
        }
    }

    private int getColorForXValue(int index) {
        if (index >= labelColors.size()) return mXAxis.getTextColor();

        if (index < 0) return mXAxis.getTextColor();

        return labelColors.get(index);
    }
}

 

MainActivity

Barchart를 다룰 java에 다음과 같은 코드를 입력합니다.

package com.example.recycleviewexample;


import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

    private final String TAG = MainActivity.class.getSimpleName();
    List<Integer> labelColors,colors;
    BarChart barChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        barChart = findViewById(R.id.graph);

		//setting barchart
        ArrayList<BarEntry> dataVals = new ArrayList<>();
        dataVals.add(new BarEntry(0,100));
        dataVals.add(new BarEntry(1,100));
        dataVals.add(new BarEntry(2,100));
        dataVals.add(new BarEntry(3,100));
        dataVals.add(new BarEntry(4,100));
        dataVals.add(new BarEntry(5,50));

        BarDataSet barDataSet = new BarDataSet(dataVals,"Dataset");
        BarData barData = new BarData();
        barData.addDataSet(barDataSet);

        barChart.setData(barData);
        barChart.invalidate();
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


		//add color list 
        List<Integer> colors = new ArrayList<>();
        colors.add(Color.rgb(0,0,0));
        colors.add(Color.rgb(255,0,0));
        colors.add(Color.rgb(0,255,0));
        colors.add(Color.rgb(0,0,255));
        colors.add(Color.rgb(125,125,125));
        colors.add(Color.rgb(200,0,100));

		//xlabel custom
        barChart.setXAxisRenderer(new ColoredLabelXAxisRenderer(barChart
        .getViewPortHandler(),barChart
        .getXAxis(),barChart
        .getTransformer(YAxis.AxisDependency.LEFT),colors));

    }

    //!--end
}

 

 

결과

이런식으로 볼 수 있습니다.

혹시 궁금한 점이 있다면 댓글 남겨주세요~! 

도움이 되셨다면 좋아요 부탁드려요