我想在图表行的x轴标签上添加背景色,并将y轴放在网格线上,如屏幕截图所示。在不定制库的情况下实现这一点是可能的吗?
最佳答案
我不想破坏这个库,所以我不得不扩展一些类并重写一些方法来满足我的需求。我所做的如下:
扩展Xaxis类并重写:
private int mXAxisLabelBackgroundColor = Color.argb(200, 140, 234, 255);
/**
* boolen used to enable or disable label background, default is enabled
*/
private boolean mEnableLabelBackground = false;
public CustomXAxis(){
super();
}
public void setLabelBackgroundColor(int color){
mXAxisLabelBackgroundColor = color;
}
public void setLabelBackgroundColor(String colorHex){
mXAxisLabelBackgroundColor = Color.parseColor(colorHex);
}
public int getXAxisLabelBackgroundColor(){
return mXAxisLabelBackgroundColor;
}
/**
* Enable/disable X Axis label background, default is disabled.
* @param enable
*/
public void setDrawLabelBackground(boolean enable){
mEnableLabelBackground = enable;
}
/**
*
* @return boolean true if drawing label background is enabled otherwise false
*/
public boolean isDrawLabelBackgroundEnabled(){
return mEnableLabelBackground;
}
扩展xaxisRenderer并覆盖DrawLabels(画布C,浮点位置)。在画标签之前画一个矩形。
if (((CustomXAxis)mXAxis).isDrawLabelBackgroundEnabled()) {
drawLabelBackground(c);
}
扩展yaxis,只需添加一个访问器和mutator来设置网格线上下的yaxis标签。
private float mYLabelPosition = 0f;
public CustomYAxisRight(){
super(AxisDependency.RIGHT);
}
/**
* Sets the label position above or below the gridline.
* <p>use negative number to set label position above gridline.</p>
* @param position
*/
public void setYLabelPosition(float position){
mYLabelPosition = position;
}
public float getYLabelPosition(){
return mYLabelPosition;
}
扩展YaxisRenderer并覆盖DrawyLabels(画布C,float fixedPosition,float[]位置,float offset)
c.drawText(text, fixedPosition, positions[i * 2 + 1] + (offset+((CustomYAxisRight)mYAxis).getYLabelPosition()), mAxisLabelPaint);
我还想在图表从0开始时显示Y轴标签0的网格线。
覆盖renderGridlines(画布C)并在绘制其他线之前绘制一条线。
if (mYAxis.isStartAtZeroEnabled()) {
mTrans.pointValuesToPixel(position);
gridLinePath.moveTo(mViewPortHandler.offsetLeft(), mViewPortHandler.contentBottom() - 1f);
gridLinePath.lineTo(mViewPortHandler.contentRight(), mViewPortHandler.contentBottom() - 1f);
// draw a path because lines don't support dashing on lower android versions
c.drawPath(gridLinePath, mGridPaint);
gridLinePath.reset();
}
最后扩展线条图并覆盖:
@Override
protected void init() {
super.init();
mAxisRight = new CustomYAxisRight();
mXAxis = new CustomXAxis();
mAxisRendererRight = new CustomYAxisRenderer(mViewPortHandler,mAxisRight,mRightAxisTransformer);
mXAxisRenderer = new CustomXAxisRenderer(mViewPortHandler, mXAxis, mLeftAxisTransformer);
}
@Override
public void setViewPortOffsets(final float left, final float top, final float right, final float bottom) {
mCustomViewPortEnabled = true;
if (((CustomXAxis)mXAxis).isDrawLabelBackgroundEnabled()){
if (bottom == 0){
//we have to leave a space for the labels to draw
_bottomOffset = 80f;
}
}
post(new Runnable() {
@Override
public void run() {
mViewPortHandler.restrainViewPort(left, top, right, _bottomOffset);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
});
}