我试图通过扩展LineChart类并覆盖onDraw方法在LineChart的极限线之间绘制颜色。我在https://github.com/PhilJay/MPAndroidChart/issues/485中看到了这一点,其中在画布上仅绘制了彩色矩形:
public class CustomLineChart extends LineChart {
protected Paint mYAxisZonePaint;
protected String[] arrayColors = {"#FFFFFF","#F4D03F","#F5B041","#EB984E","#DC7633"};
@Override
protected void init() {
super.init();
mYAxisZonePaint = new Paint();
mYAxisZonePaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
List<LimitLine> limitLines = mAxisLeft.getLimitLines();
if (limitLines == null || limitLines.size() < 4){
super.onDraw(canvas);
return;
}
float[] pts = new float[2];
float startPts = 0;
for (int i = 0; i < limitLines.size(); i++) {
pts[0] = limitLines.get(i).getLimit();
pts[1] = startPts;
mLeftAxisTransformer.pointValuesToPixel(pts);
mYAxisZonePaint.setColor(Color.parseColor(arrayColors[i]));
canvas.drawRect(mViewPortHandler.contentLeft(), pts[1], mViewPortHandler.contentRight(), pts[0], mYAxisZonePaint);
startPts = limitLines.get(i).getLimit();
}
super.onDraw(canvas);
}
}
上面的代码无法在线条图的数据后面绘制彩色矩形作为背景,如此处所示
但是,当我在Y轴上滚动时,矩形将“溢出”到绘制X轴标签的区域,如该图所示
我应该如何绘制彩色背景,以使其不着色绘制X轴标签的区域,就像如何在X轴上方截断线数据和极限线一样?
答案 0 :(得分:0)
似乎我已经找到解决问题的方法。在onDraw方法内部,我应该限制以下绘制操作可以写入的区域。我在onDraw方法中添加了以下内容:
@Override
protected void onDraw(Canvas canvas) {
List<LimitLine> limitLines = mAxisLeft.getLimitLines();
// Saves current canvas
int clipRestoreCount = canvas.save();
// Makes sure that the colored background cannot be drawn outside the content-rect. Otherwise the colored background would be drawn above and beneath the graph "borders".
canvas.clipRect(mViewPortHandler.getContentRect());
if (limitLines == null || limitLines.size() < 4){
super.onDraw(canvas);
return;
}
float[] pts = new float[2];
float startPts = 0;
for (int i = 0; i < limitLines.size(); i++) {
pts[0] = limitLines.get(i).getLimit();
pts[1] = startPts;
mLeftAxisTransformer.pointValuesToPixel(pts);
mYAxisZonePaint.setColor(Color.parseColor(arrayColors[i]));
canvas.drawRect(mViewPortHandler.contentLeft(), pts[1], mViewPortHandler.contentRight(), pts[0], mYAxisZonePaint);
startPts = limitLines.get(i).getLimit();
}
// Removes the clipping rectangles so rest of graph elements can be drawn (like x-axis/y-axis labels)
canvas.restoreToCount(clipRestoreCount);
super.onDraw(canvas);
}