Swift - 自定义iOS Charts中PieEntry标签以显示小时和分钟
Hey there! I’ve run into this exact label formatting challenge when working with PieCharts for time tracking—so let me share how to get those decimal values like 15.50 showing up as 15小时30分钟 instead.
核心思路:自定义ValueFormatter
Most PieChart libraries (like the widely-used MPAndroidChart) let you fully control how entry values are displayed using a custom ValueFormatter. This lets you convert float-based hour values into the human-readable time format you want.
Step 1: 创建自定义格式化器
Make a class that extends the library’s ValueFormatter and overrides the getFormattedValue method to handle the decimal-to-time conversion:
// Java版本 public class TimeLabelFormatter extends ValueFormatter { @Override public String getFormattedValue(float value) { // 提取整数部分作为小时 int hours = (int) value; // 把小数部分转换成分钟(0.5小时 = 30分钟) int minutes = Math.round((value - hours) * 60); return String.format("%d小时%d分钟", hours, minutes); } }
If you’re using Kotlin, the code is even cleaner:
// Kotlin版本 class TimeLabelFormatter : ValueFormatter() { override fun getFormattedValue(value: Float): String { val hours = value.toInt() val minutes = ((value - hours) * 60).roundToInt() return "${hours}小时${minutes}分钟" } }
Step 2: 将格式化器绑定到PieChart
Once your formatter is ready, attach it to your PieDataSet (the collection of your chart entries):
// Java示例 // 假设你已经创建好了entries列表 PieDataSet dataSet = new PieDataSet(entries, "24小时时间分布"); // 绑定自定义格式化器 dataSet.setValueFormatter(new TimeLabelFormatter()); // 组装PieData并设置给图表 PieData pieData = new PieData(dataSet); yourPieChart.setData(pieData); // 刷新图表以应用更改 yourPieChart.invalidate();
额外优化:避免浮点精度问题
If you calculate time spans in minutes first (instead of converting to decimal hours), adjust the formatter to work with total minutes directly—this eliminates any floating-point inaccuracies:
public class TimeLabelFormatter extends ValueFormatter { @Override public String getFormattedValue(float value) { int totalMinutes = (int) value; int hours = totalMinutes / 60; int minutes = totalMinutes % 60; return String.format("%d小时%d分钟", hours, minutes); } }
Just ensure your Entry objects store total minutes instead of decimal hours when using this version.
That’s it! This approach gives you full control over how each entry’s label is displayed, and it’s the standard way to customize value formatting in most PieChart libraries.
内容的提问来源于stack exchange,提问作者Irving Gonzalez

