如何在android中绘制饼图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20835628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw a pie chart in android
提问by Smile
I'd like to draw a pie chart in my android application. Would you please suggest me a way to do that in a simple way ? I have written a view class for that purpose but it's not satisfying. So I would appreciate if you tell me a good and high performance chart library.
我想在我的 android 应用程序中绘制一个饼图。你能建议我一种简单的方法吗?我为此目的编写了一个视图类,但它并不令人满意。所以如果你告诉我一个好的和高性能的图表库,我将不胜感激。
回答by Raghunandan
Download the jar from
从以下位置下载 jar
http://www.achartengine.org/content/download.html
http://www.achartengine.org/content/download.html
Add the jar to the projects lib folder. There is a sample also provided by the developers. You can check that and modify the same as you wish.
将 jar 添加到项目 lib 文件夹中。开发人员还提供了一个示例。您可以检查并根据需要进行修改。
There is also a demo @
还有一个演示@
http://www.achartengine.org/content/demo.html
http://www.achartengine.org/content/demo.html
The docs
文档
http://www.achartengine.org/content/javadoc/org/achartengine/chart/PieChart.html
http://www.achartengine.org/content/javadoc/org/achartengine/chart/PieChart.html
Example:
例子:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
The Activity class
活动类
public class AChartEnginePieChartActivity extends Activity {
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private static double[] VALUES = new double[] { 10, 11, 12, 13 };
private static String[] NAME_LIST = new String[] { "A", "B", "C", "D" };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
}
@Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was clicked",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was long pressed", Toast.LENGTH_SHORT);
return false;
}
else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT);
return true;
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
else {
mChartView.repaint();
}
}
}
回答by nstosic
Alternatively, if you don't want to use thrid-party libraries, you can use this formula to get points on the circle, given radius r
:
或者,如果您不想使用第三方库,您可以使用此公式在给定半径的情况下获取圆上的点r
:
x = r * Math.cos(2 * Math.PI) //This will give you r
y = r * Math.sin(2 * Math.PI) //This will give you 0
For other points of the circle you need to modify your cosine argument, for example:
对于圆的其他点,您需要修改余弦参数,例如:
x = r * Math.cos(2 * Math.PI / 6) //This will give you r/2
y = r * Math.sin(2 * Math.PI / 6) //This will give you r*sqrt(3/2)
If you want to fill out the entire circle with a fixed step n:
如果你想用固定步长 n 填满整个圆圈:
for(int i=0;i<n;i++) {
x = r * Math.cos(2 * Math.PI * i / n)
y = r * Math.sin(2 * Math.PI * i / n)
//Draw PointF(x,y)
}
回答by marshallino16
Another library is PAcPie Char, you can take a look :
另一个库是 PacPie Char,你可以看看:
https://github.com/marshallino16/PacPieChart-Android
https://github.com/marshallino16/PacPieChart-Android
I'm still writing it but at least, it's a beginning
我还在写,但至少,这是一个开始
回答by Phant?maxx
I think your best friend is aChartEngine.
It's easy to use and provides a wide range of charts to display.
我认为你最好的朋友是aChartEngine。
它易于使用并提供了广泛的图表来显示。
Example of a pie chart:
饼图示例:
回答by eli
If you want to have best Pie Chart do as follows:
1. Open build.gradle(Modul: app) add dependence implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
如果你想拥有最好的饼图,请执行以下操作: 1. 打开 build.gradle(Modul: app) 添加依赖 implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
2.Create Your_Layout as:
2.创建 Your_Layout 为:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center_vertical"
android:orientation="vertical">
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/piechart_1"
android:layout_width="match_parent"
android:layout_height="300sp">
</com.github.mikephil.charting.charts.PieChart>
</LinearLayout>
Open Your activity file and paste the following codes:
public class YourActivity extends AppCompatActivity{ protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.Your_layout); setPieChart(); } public void setPieChart() { this.pieChart = pieChart; pieChart.setUsePercentValues(true); pieChart.getDescription().setEnabled(true); pieChart.setExtraOffsets(5,10,5,5); pieChart.setDragDecelerationFrictionCoef(0.9f); pieChart.setTransparentCircleRadius(61f); pieChart.setHoleColor(Color.WHITE); pieChart.animateY(1000, Easing.EasingOption.EaseInOutCubic); ArrayList<PieEntry> yValues = new ArrayList<>(); yValues.add(new PieEntry(34f,"Ilala")); yValues.add(new PieEntry(56f,"Temeke")); yValues.add(new PieEntry(66f,"Kinondoni")); yValues.add(new PieEntry(45f,"Kigamboni")); PieDataSet dataSet = new PieDataSet(yValues, "Desease Per Regions"); dataSet.setSliceSpace(3f); dataSet.setSelectionShift(5f); dataSet.setColors(ColorTemplate.COLORFUL_COLORS); PieData pieData = new PieData((dataSet)); pieData.setValueTextSize(10f); pieData.setValueTextColor(Color.YELLOW); pieChart.setData(pieData); //PieChart Ends Here } }
打开您的活动文件并粘贴以下代码:
public class YourActivity extends AppCompatActivity{ protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.Your_layout); setPieChart(); } public void setPieChart() { this.pieChart = pieChart; pieChart.setUsePercentValues(true); pieChart.getDescription().setEnabled(true); pieChart.setExtraOffsets(5,10,5,5); pieChart.setDragDecelerationFrictionCoef(0.9f); pieChart.setTransparentCircleRadius(61f); pieChart.setHoleColor(Color.WHITE); pieChart.animateY(1000, Easing.EasingOption.EaseInOutCubic); ArrayList<PieEntry> yValues = new ArrayList<>(); yValues.add(new PieEntry(34f,"Ilala")); yValues.add(new PieEntry(56f,"Temeke")); yValues.add(new PieEntry(66f,"Kinondoni")); yValues.add(new PieEntry(45f,"Kigamboni")); PieDataSet dataSet = new PieDataSet(yValues, "Desease Per Regions"); dataSet.setSliceSpace(3f); dataSet.setSelectionShift(5f); dataSet.setColors(ColorTemplate.COLORFUL_COLORS); PieData pieData = new PieData((dataSet)); pieData.setValueTextSize(10f); pieData.setValueTextColor(Color.YELLOW); pieChart.setData(pieData); //PieChart Ends Here } }
It Will Give you Pie Chart shown Below;
The Library can also be used for Drawing Bar Graphs, LineGraphs,Horizontal Bar Graphs Etc
该库还可用于绘制条形图、线图、水平条形图等
回答by M Karimi
Open up build.gradle (module:app) and add the library in the dependencies.
打开 build.gradle (module:app) 并在依赖项中添加库。
implementation 'com.github.lecho:hellocharts-library:1.5.8@aar'
Next you need to open up build.gradle (Project) and add Jcenter because this library is available through it.
接下来你需要打开 build.gradle (Project) 并添加 Jcenter 因为这个库可以通过它获得。
allprojects {
repositories {
google()
jcenter()
}
}
}
Now sync your project by clicking on Sync Now.
现在通过单击立即同步来同步您的项目。
Open up activity_main.xml and add the following code for Android pie chart view.
打开activity_main.xml,为Android饼图视图添加以下代码。
< ?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.codingdemos.codingdemos.MainActivity">
<lecho.lib.hellocharts.view.PieChartView
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
< /LinearLayout>
Here is the code for MainActivity.java file.
这是 MainActivity.java 文件的代码。
public class MainActivity extends AppCompatActivity {
PieChartView pieChartView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pieChartView = findViewById(R.id.chart);
List pieData = new ArrayList<>();
pieData.add(new SliceValue(15, Color.BLUE).setLabel("Q1: "));
pieData.add(new SliceValue(25, Color.GRAY).setLabel("Q2: "));
pieData.add(new SliceValue(10, Color.RED).setLabel("Q3: "));
pieData.add(new SliceValue(60, Color.MAGENTA).setLabel("Q4: "));
PieChartData pieChartData = new PieChartData(pieData);
pieChartData.setHasLabels(true).setValueLabelTextSize(14);
pieChartData.setHasCenterCircle(true).setCenterText1("Sales in million").setCenterText1FontSize(20).setCenterText1Color(Color.parseColor("#0097A7"));
pieChartView.setPieChartData(pieChartData);
}
}
you can see https://www.codingdemos.com/android-pie-chart-tutorial/for more description.
您可以查看https://www.codingdemos.com/android-pie-chart-tutorial/了解更多说明。
回答by Alvi
If you don't want to use any third party library,try sample form google. They provide a sample to draw pie chart in their Custom Drawing documentation.
如果您不想使用任何第三方库,请尝试示例表单 google。他们在自定义绘图文档中提供了绘制饼图的示例。