问题
This answer to a similar question shows how to fill the area between two lines on an MpAndroidChart LineChart.
However, rather than using LineChart, I am using CombinedChart (as I also have bar data to show). But applying the above solution to a CombinedChart results in this exception:
java.lang.ClassCastException: org.example.MyLineLegendRenderer cannot be cast to com.github.mikephil.charting.renderer.CombinedChartRenderer at com.github.mikephil.charting.charts.CombinedChart.setData(CombinedChart.java:96)
So I have looked at CombinedChartRenderer but (unlike LineChartRenderer), it does not seem to contain any functionality for filling.
So how can I fill the space between two lines on a CombinedChart?
回答1:
You can override the createRenderers()
method in the CombinedChartRenderer
class. This way you can use your own renderer for each and every type of graph that you use in the your CombinedChart
.
It will be something like this :
public class MyCombinedChartRenderer extends CombinedChartRenderer {
public MyCombinedChartRenderer(CombinedChart chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
@Override
public void createRenderers() {
this.mRenderers.clear();
CombinedChart chart = (CombinedChart)this.mChart.get();
if (chart != null) {
CombinedChart.DrawOrder[] orders = chart.getDrawOrder();
CombinedChart.DrawOrder[] var3 = orders;
int var4 = orders.length;
for(int var5 = 0; var5 < var4; ++var5) {
CombinedChart.DrawOrder order = var3[var5];
switch(order) {
case BAR:
if (chart.getBarData() != null) {
this.mRenderers.add(new BarChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
}
break;
case BUBBLE:
if (chart.getBubbleData() != null) {
this.mRenderers.add(new BubbleChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
}
break;
case LINE:
if (chart.getLineData() != null) {
// replace with you own Line chart renderer
//this.mRenderers.add(new LineChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
this.mRenderers.add(new MyLineChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
}
break;
case CANDLE:
if (chart.getCandleData() != null) {
this.mRenderers.add(new CandleStickChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
}
break;
case SCATTER:
if (chart.getScatterData() != null) {
this.mRenderers.add(new ScatterChartRenderer(chart, this.mAnimator, this.mViewPortHandler));
}
}
}
}
}
}
In the above code, in the switch
block when case LINE:
is encountered, we replace the default renderer with our own version : MyLineChartRenderer
.
Then finally in your Activity code, you can use this renderer with your CombinedChart :
CombinedChart combinedChart = (CombinedChart) findViewById(R.id.barChart);
combinedChart.setRenderer(new MyCombinedChartRenderer(combinedChart, combinedChart.getAnimator(), combinedChart.getViewPortHandler()));
来源:https://stackoverflow.com/questions/49986048/mpandroidchart-how-to-fill-area-between-two-lines-on-a-combinedchart