首页 > 解决方案 > MPAndroidChart 正确使用 getPixelForValues 为图表渐变颜色

问题描述

我正在尝试LineChart根据this issuey的值设置 a 的颜色渐变。计划是制作一个只覆盖整个事物一次的渐变。

   override fun createChartGradient(myEntities: List<MyEntity>, chart: LineChart): LinearGradient {
       val transformer = Transformer(chart.viewPortHandler)
       val entries: List<Entry> = createEntriesFrom(myEntities) // this works fine, the chart is plotted alright
       val pixelXValues = entries.map { transformer.getPixelForValues(it.x, it.y).x.toFloat() }.toFloatArray()
       val colors = calculateColorsBasedOnValues(myEntities) // this works fine, I can set the fill color of points with this. 
       return LinearGradient(pixelXValues.first(), 0f, pixelXValues.last(), 0f, colors.toIntArray(), pixelXValues.lerp(), Shader.TileMode.REPEAT)
   }

   private fun FloatArray.lerp(): FloatArray {
       val total = this.last() - this.first()
       return this.map { ((it - this.first()) / total) }.toFloatArray()
   }

哪个是分配给图表的

    val gradient = lineChartService.createChartGradient(entities, chart)
    chart.renderer.paintRender.shader = gradient

我很清楚,我必须在放大或缩小时更新它,但现在即使完全缩小,我也很难让它工作,在这种情况下,图表似乎重复着色器 5 次 - 但基于我的计算我应该只涵盖整个事情一次。

我附加了一个调试器,lerp函数的输出是从 0 到 1,包括 0 到 1。

我在做什么错getPixelForValuesLinearGradient

标签: androidmpandroidchartlinear-gradients

解决方案


推荐阅读