【问题标题】:MPAndroidChart - all pieces of the pie chart are the same colourMPAndroidChart - 饼图的所有部分都是相同的颜色
【发布时间】:2018-03-18 13:58:17
【问题描述】:

我正在使用 MPAndroidChart (https://github.com/PhilJay/MPAndroidChart) 库来生成饼图。我遵循了多个教程,包括 wiki 页面,但是当我创建我的饼图时,所有的部分都是相同的颜色。知道如何解决这个问题吗?

代码:

PieChart mChart = (PieChart) findViewById(R.id.piechart);

List<PieEntry> pieChartEntries = new ArrayList<>();

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

PieDataSet set = new PieDataSet(pieChartEntries, "Emotion Results");
PieData data = new PieData(set);
mChart.setData(data);
set.setColors(R.color.pieColour1,R.color.pieColour2,R.color.pieColour3,R.color.pieColour4,R.color.pieColour5,R.color.pieColour6,R.color.pieColour7,R.color.pieColour8);
mChart.invalidate();

【问题讨论】:

    标签: android mpandroidchart


    【解决方案1】:

    文档说:

    当添加一些额外的样式时,生成的 PieChart 带有 上面使用的数据可能与此类似

    这些不是真正的颜色,只是颜色的标签:

    pieChartEntries.add(new PieEntry(18.5f, "Green"));
    pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
    pieChartEntries.add(new PieEntry(24.0f, "Red"));
    pieChartEntries.add(new PieEntry(30.8f, "Blue"));
    

    要为您使用的饼图添加颜色:

    set.setColors(new int[]{Color.parseColor("#FF32DA64"),
                        Color.parseColor("#FF32DAD4"),
                        Color.parseColor("#FFB853F2"),
                        Color.parseColor("#FFF2ED53")});
    

    或者您可以使用以下模板之一:

    set.setColors(ColorTemplate.COLORFUL_COLORS);
    

    编辑:

    我刚刚看到您正在使用资源中的颜色,如果您检查 setColors 方法,您应该会看到:

    如果您使用资源中的颜色,请确保颜色 已经准备好了(通过调用 getResources().getColor(...))

    因此,在您的情况下,您需要先将资源解析为 Color 对象,然后再将它们添加到 set

    【讨论】:

    • 是的,“编辑”解决了我的问题。我做了 set.setColors(getResources().getColor(R.color.pieColour1), getResources().getColor(R.color.pieColour2)...) 并修复了它。谢谢李维斯
    • 很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2016-05-13
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2018-09-21
    • 2011-06-10
    相关资源
    最近更新 更多