首先感謝網(wǎng)上大神們分享MPAndroidChart的代碼及實際問題的解決方式。
下面分享的代碼是本人在開發(fā)過程中用到的屬性及解釋,有個別屬性是在網(wǎng)上找了好久也沒找到,希望分享出來對大家有幫助。
貼代碼:
/**
* 設(shè)置餅圖樣式
*
*@parampieChart
*@parampieValues
*@paramtitle
*@paramshowLegend是否顯示圖例
*/
public static voidsetPieChart(PieChart pieChart,Map pieValues,String title, booleanshowLegend) {
pieChart.setUsePercentValues(true);//設(shè)置使用百分比
pieChart.getDescription().setEnabled(false);//設(shè)置描述
pieChart.setExtraOffsets(15f,5f,15f,5f);//餅圖左上右下邊距
pieChart.setCenterText(title);//設(shè)置環(huán)中的文字
pieChart.setCenterTextSize(6f);//設(shè)置環(huán)中文字的大小
pieChart.setDrawCenterText(false);//不設(shè)置繪制環(huán)中文字
pieChart.setRotationAngle(120f);//設(shè)置旋轉(zhuǎn)角度
pieChart.setDrawHoleEnabled(false);//是否設(shè)置中間的圓環(huán)
//圖例設(shè)置
Legend legend = pieChart.getLegend();
if(showLegend) {
legend.setEnabled(true);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
legend.setDrawInside(false);
legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
legend.setTextSize(8f);
legend.setYOffset(10f);//下邊距
legend.setTextColor(R.color.black_light);
legend.setXEntrySpace(2f);
legend.setYEntrySpace(2f);
}else{
legend.setEnabled(false);
}
//設(shè)置餅圖數(shù)據(jù)
setPieChartData(pieChart,pieValues);
pieChart.animateX(1500,Easing.EasingOption.EaseInOutQuad);//數(shù)據(jù)顯示動畫
}
/**
* 設(shè)置餅圖數(shù)據(jù)源
*/
private static voidsetPieChartData(PieChart pieChart,Map pieValues) {
ArrayList entries =newArrayList<>();
Set set = pieValues.entrySet();
Iterator it = set.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
entries.add(newPieEntry(Float.valueOf(entry.getValue().toString()),entry.getKey().toString()));
}
PieDataSet dataSet =newPieDataSet(entries,"");
dataSet.setSliceSpace(1f);//設(shè)置餅塊之間的間隔
dataSet.setSelectionShift(5f);//設(shè)置餅塊選中時偏離餅圖中心的距離
dataSet.setColors(PIE_COLORS);//設(shè)置餅塊的顏色
dataSet.setValueLinePart1OffsetPercentage(80f);//數(shù)據(jù)連接線距圖形片內(nèi)部邊界的距離,為百分?jǐn)?shù)
dataSet.setValueLinePart1Length(0.55f);//水平方向線的長度
dataSet.setValueLinePart2Length(0.5f);//線的長度
dataSet.setValueLineColor(Color.RED);//設(shè)置連接線的顏色
dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);//餅圖數(shù)據(jù)在外面
PieData pieData =newPieData(dataSet);
pieData.setValueFormatter(newPercentFormatter());//追加%號
pieData.setValueTextSize(8f);//比例字體大小
pieData.setValueTextColor(Color.RED);//比例顏色
pieData.setDrawValues(true);//百分比及連線是否顯示
pieChart.setData(pieData);
pieChart.setEntryLabelTextSize(10f);//餅塊文字描述
pieChart.setEntryLabelColor(Color.RED);//餅塊文字顏色
pieChart.highlightValues(null);
pieChart.invalidate();//刷新
}