在LineChart

时间:2017-02-03 09:46:30

标签: android charts linechart mpandroidchart

我使用库MPAndroidChart创建了一个LineChart,一切都很好。

现在我要做的是为图表上的每个条目显示一个drawable(图像)而不是默认的圆圈。

我已经从API尝试了很多选项,但没有运气。

谁能告诉我怎么办?

3 个答案:

答案 0 :(得分:4)

最后在尝试了很多事情之后,在@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);
}

希望这有助于某人。

答案 1 :(得分:1)

您可以使用drawable创建条目,并在图形上绘制而不是圆形。

new Entry(i, value, drawable)

答案 2 :(得分:0)

我也遇到了这个问题,但是有一些更具体的要求:

  1. 仅在图表上的特定点绘制圆圈。
  2. 具有在不同情况下使用不同可绘制对象的灵活性。

最后,我设法实现了这一目标:

enter image description here

每个圆实际上是一个常规可绘制对象,并且可以用其他任何对象替换。

以另一种方式解决:

1。创建一个Entry子类,该子类将可绘制对象作为参数。

/**
 * Represents an [Entry] which is able to use drawables (including different drawables for different points) instead of the circle.
 * For the points where you don't need points use a regular [Entry].
 */

class DrawableCircleEntry @JvmOverloads constructor(
        @DrawableRes val circleDrawableRes: Int,
        x: Float,
        y: Float,
        icon: Drawable? = null,
        data: Any? = null
) : Entry(x, y, icon, data) 

2。创建一个自定义渲染,

    如果输入是DrawableCircleEntry类型,
  • 绘制可绘制对象而不是圆形。

  • 如果尝试将其作为常规条目,则不要画圆。

    internal class LineChartCustomCirclesRenderer(private val context: Context, lineChart: LineChart
      ) : LineChartRenderer(lineChart, lineChart.animator, lineChart.viewPortHandler) {
    
      // Contains (left, top) coordinates of the next circle which has to be drawn
      private val circleCoordinates = FloatArray(2)
      // Cached drawables
      private val drawablesCache = SparseArray<Drawable>()
    
      override fun drawCircles(canvas: Canvas) {
          val phaseY = mAnimator.phaseY
          circleCoordinates[0] = 0f
          circleCoordinates[1] = 0f
          val dataSets = mChart.lineData.dataSets
    
          dataSets.forEach { dataSet ->
              if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0)
                  return@forEach
    
              val transformer = mChart.getTransformer(dataSet.axisDependency)
              mXBounds[mChart] = dataSet
              val boundsRangeCount = mXBounds.range + mXBounds.min
    
              for (i in mXBounds.min..boundsRangeCount) {
                  // don't do anything in case entry is not type of DrawableCircleEntry
                  val entry = dataSet.getEntryForIndex(i) as? DrawableCircleEntry
                          ?: continue
                  circleCoordinates[0] = entry.x
                  circleCoordinates[1] = entry.y * phaseY
    
                  transformer.pointValuesToPixel(circleCoordinates)
    
                  if (!mViewPortHandler.isInBoundsRight(circleCoordinates[0])) break
                  if (!mViewPortHandler.isInBoundsLeft(circleCoordinates[0]) || !mViewPortHandler.isInBoundsY(circleCoordinates[1])) continue
    
                  // Drawable radius is taken as `dataSet.circleRadius`
                  val radius = dataSet.circleRadius
    
                  // Retrieve the drawable, center it and draw on canvas
                  getDrawable(entry.circleDrawableRes)?.run {
                      setBounds((circleCoordinates[0] - radius).roundToInt(), (circleCoordinates[1] - radius).roundToInt(),
                              (circleCoordinates[0] + radius).roundToInt(), (circleCoordinates[1] + radius).roundToInt())
                      draw(canvas)
                  }
              }
          }
      }
    
    
      private fun getDrawable(@DrawableRes drawableRes: Int): Drawable? {
          drawablesCache[drawableRes]?.let {
              return it
          }
          return ContextCompat.getDrawable(context, drawableRes)
                  .also { drawablesCache.append(drawableRes, it) }
      }
    

    }

3。为数据集启用圆并设置所需的半径。可绘制对象的大小将为radius*2

 dataSet.setDrawCircles(true)
 dataSet.circleRadius = 3f

4。构造Entries时,为不需要画圆的点创建一个普通Entry,并在需要一个圆时创建一个DrawableCircleEntry。 例如,

    ...
    val entry = when {
        someCondition ->  DrawableCircleEntry(R.drawable.your_awesome_drawable, floatIndex, floatValue)
        anotherCondition ->  DrawableCircleEntry(R.drawable.your_another_drawable, floatIndex, floatValue)
        else -> Entry(floatIndex, floatValue)
    }
    ...
  1. 在我的情况下,一个可绘制对象看起来像:

<item>
    <shape
        android:shape="ring"
        android:thickness="@dimen/chart_circle_stroke_thickness"
        android:useLevel="false">
        <solid android:color="#497EFF" />
    </shape>
</item>

但是可以是其他任何

享受。