其他分享
首页 > 其他分享> > android-在LineChart上显示图像而不是圆形

android-在LineChart上显示图像而不是圆形

作者:互联网

我已经使用库MPAndroidChart创建了LineChart,并且一切正常.

现在,我要为图表上的每个条目显示一个可绘制的(图像)而不是默认的圆圈.

我从API尝试了很多选择,但是没有运气.

谁能告诉我该怎么做?

解决方法:

最后,在尝试了很多事情之后,借助@David Rawson的建议和此帖子MPAndroidChart LineChart custom highlight drawable

我设法创建了一个自定义渲染器,该渲染器用提供的图像替换了图表中的默认圆形图像.

以下是解决方案的代码片段.

class ImageLineChartRenderer extends LineChartRenderer {
private final LineChart lineChart;
private final Bitmap image;


ImageLineChartRenderer(LineChart chart, ChartAnimator animator, ViewPortHandler viewPortHandler, Bitmap image) {
    super(chart, animator, viewPortHandler);
    this.lineChart = chart;
    this.image = image;
}

private float[] mCirclesBuffer = new float[2];

@Override
protected void drawCircles(Canvas c) {
    mRenderPaint.setStyle(Paint.Style.FILL);
    float phaseY = mAnimator.getPhaseY();
    mCirclesBuffer[0] = 0;
    mCirclesBuffer[1] = 0;
    List<ILineDataSet> dataSets = mChart.getLineData().getDataSets();

    //Draw bitmap image for every data set with size as radius * 10, and store it in scaled bitmaps array
    Bitmap[] scaledBitmaps = new Bitmap[dataSets.size()];
    float[] scaledBitmapOffsets = new float[dataSets.size()];
    for (int i = 0; i < dataSets.size(); i++) {
        float imageSize = dataSets.get(i).getCircleRadius() * 10;
        scaledBitmapOffsets[i] = imageSize / 2f;
        scaledBitmaps[i] = scaleImage((int) imageSize);
    }

    for (int i = 0; i < dataSets.size(); i++) {
        ILineDataSet dataSet = dataSets.get(i);

        if (!dataSet.isVisible() || !dataSet.isDrawCirclesEnabled() || dataSet.getEntryCount() == 0)
            continue;

        mCirclePaintInner.setColor(dataSet.getCircleHoleColor());
        Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());
        mXBounds.set(mChart, dataSet);


        int boundsRangeCount = mXBounds.range + mXBounds.min;
        for (int j = mXBounds.min; j <= boundsRangeCount; j++) {
            Entry e = dataSet.getEntryForIndex(j);
            if (e == null) break;
            mCirclesBuffer[0] = e.getX();
            mCirclesBuffer[1] = e.getY() * phaseY;
            trans.pointValuesToPixel(mCirclesBuffer);
            if (!mViewPortHandler.isInBoundsRight(mCirclesBuffer[0]))
                break;
            if (!mViewPortHandler.isInBoundsLeft(mCirclesBuffer[0]) || !mViewPortHandler.isInBoundsY(mCirclesBuffer[1]))
                continue;

            if (scaledBitmaps[i] != null) {
                c.drawBitmap(scaledBitmaps[i],
                        mCirclesBuffer[0] - scaledBitmapOffsets[i],
                        mCirclesBuffer[1] - scaledBitmapOffsets[i],
                        mRenderPaint);
            }
        }
    }

}


private Bitmap scaleImage(int radius) {
    return Bitmap.createScaledBitmap(image, radius, radius, false);
}

希望这对某人有帮助.

标签:mpandroidchart,linechart,android,charts
来源: https://codeday.me/bug/20191010/1885970.html