是否可以限制在MPAndroidChart中在XAxis上绘制的LimitLine的高度?

时间:2017-01-31 10:01:15

标签: android mpandroidchart

我正在使用MPAndroidChart库绘制带有两个YAxis的LineChart,以显示不同值的两个图形。我只是想在这两个图之间显示LimitLine。如果是,那么可能吗?Sample Image Attached

1 个答案:

答案 0 :(得分:0)

是的。您应该扩展XAxisRenderer类并重写必要的方法。

public class CustomXAxisRenderer extends XAxisRenderer {

private float[] mLimitLineSegmentsBuffer = new float[4];
private Path mLimitLinePath = new Path();
private float topOffset;
private float bottomOffset;


public CustomXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) {
    super(viewPortHandler, xAxis, trans);
}

@Override
public void renderLimitLines(Canvas c) {

    List<LimitLine> limitLines = mXAxis.getLimitLines();

    if (limitLines == null || limitLines.size() <= 0)
        return;

    float[] position = mRenderLimitLinesBuffer;
    position[0] = 0;
    position[1] = 0;

    for (int i = 0; i < limitLines.size(); i++) {

        LimitLine l = limitLines.get(i);

        if (!l.isEnabled())
            continue;

        int clipRestoreCount = c.save();
        mLimitLineClippingRect.set(mViewPortHandler.getContentRect());
        mLimitLineClippingRect.inset(-l.getLineWidth(), 0.f);
        c.clipRect(mLimitLineClippingRect);

        position[0] = l.getLimit();
        position[1] = 0.f;

        mTrans.pointValuesToPixel(position);

        //Here you can count your offsets
        // topOffset = ... ;
        // bottomOffset = ...;

        renderLimitLineLine(c, l, position);
        renderLimitLineLabel(c, l, position, yOffset);

        c.restoreToCount(clipRestoreCount);
    }
}

@Override
public void renderLimitLineLine(Canvas c, LimitLine limitLine, float[] position) {
    mLimitLineSegmentsBuffer[0] = position[0];

    // Here, the offsets will be applied 
    mLimitLineSegmentsBuffer[1] = mViewPortHandler.contentTop() + topOffset;
    mLimitLineSegmentsBuffer[2] = position[0];
    mLimitLineSegmentsBuffer[3] = mViewPortHandler.contentBottom() - bottomOffset;

    mLimitLinePath.reset();
    mLimitLinePath.moveTo(mLimitLineSegmentsBuffer[0], mLimitLineSegmentsBuffer[1]);
    mLimitLinePath.lineTo(mLimitLineSegmentsBuffer[2], mLimitLineSegmentsBuffer[3]);

    mLimitLinePaint.setStyle(Paint.Style.STROKE);
    mLimitLinePaint.setColor(limitLine.getLineColor());
    mLimitLinePaint.setStrokeWidth(limitLine.getLineWidth());
    mLimitLinePaint.setPathEffect(limitLine.getDashPathEffect());

    c.drawPath(mLimitLinePath, mLimitLinePaint);
}

然后,您必须设置新的渲染器:

  mGraph.setXAxisRenderer(new CustomXAxisRenderer(mGraph.getViewPortHandler()
                , mGraph.getXAxis(), 
  mGraph.getTransformer(YAxis.AxisDependency.LEFT)));