Vico 图表 android 四舍五入到最接近的 10

问题描述 投票:0回答:1

我正在使用 vico 图表库进行 android jetpack 撰写。我想将 startAxis 的值四舍五入到最接近的 10 并更改点。例如,我想将垂直轴的值设置为 (11,21,32...) 而不是图像中的 (10,20,30...)。 enter image description here enter image description here

我尝试使用AxisValueFormatter,但它只改变标签,而不是轴点本身的位置

android kotlin graph charts android-jetpack-compose
1个回答
0
投票

为了自定义显示刻度、标签和网格线的起始轴的值,请创建 AxisItemPlacer.Vertical 的实现并重写“getLabelValues”以返回您的首选值。 vico Axes wiki 中提到了此行为。

import com.patrykandpatrick.vico.core.axis.AxisItemPlacer
import com.patrykandpatrick.vico.core.axis.AxisPosition
import com.patrykandpatrick.vico.core.axis.vertical.VerticalAxis
import com.patrykandpatrick.vico.core.chart.draw.ChartDrawContext

class MyVerticalAxisItemPlacer : AxisItemPlacer.Vertical {
    // Do ticks for 0, 10.5, 21, 31.5, etc.
    // Assuming you round the display values, these will show as 0,11,21,32,42,53...
    override fun getLabelValues(
        context: ChartDrawContext,
        axisHeight: Float,
        maxLabelHeight: Float,
        position: AxisPosition.Vertical
    ): List<Float> {
        val labelList = mutableListOf<Float>()
        // Use a maxValue relative to the maximum in your data set - axisHeight is in pixels and so is NOT useful relative to the tick values
        for (i in 0..maxValue) {
            labelList.add((i * 10.5F).toFloat())
        }
        return labelList.toList()
    }

    // Return the default implementation for the other required functions
    override fun getBottomVerticalAxisInset(
        verticalLabelPosition: VerticalAxis.VerticalLabelPosition,
        maxLabelHeight: Float,
        maxLineThickness: Float
    ): Float {
        return AxisItemPlacer.Vertical.default().getBottomVerticalAxisInset(
            verticalLabelPosition,
            maxLabelHeight,
            maxLineThickness
        )
    }
    ...
}

然后,将此自定义类的实例作为图表 startAxis 上的 itemPlacer 传递:

import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.patrykandpatrick.vico.compose.axis.vertical.rememberStartAxis
import com.patrykandpatrick.vico.compose.chart.Chart


// Use remember so a new instance is not created each time the view recomposes
val verticalItemPlacer by remember { mutableStateOf(MyVerticalAxisItemPlacer()) }
Chart(
    ...
    startAxis = rememberStartAxis(
            itemPlacer = verticalItemPlacer
        ),
    ...
)
© www.soinside.com 2019 - 2024. All rights reserved.