如何在android中绘制饼图

时间:2013-12-30 07:58:32

标签: android graph

我想在我的Android应用程序中绘制一个饼图。 请您以简单的方式向我建议一种方法吗? 我为此目的编写了一个视图类,但它并不令人满意。如果你告诉我一个优秀的高性能图表库,我将不胜感激。

7 个答案:

答案 0 :(得分:23)

下载jar

http://www.achartengine.org/content/download.html

将jar添加到项目lib文件夹中。开发人员也提供了一个示例。您可以检查并根据需要进行修改。

还有一个演示@

http://www.achartengine.org/content/demo.html

文档

http://www.achartengine.org/content/javadoc/org/achartengine/chart/PieChart.html

示例:

<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>

活动类

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();
        }
    }
}

答案 1 :(得分:16)

或者,如果您不想使用第三方库,则可以使用此公式在给定半径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

对于圆圈的其他点,您需要修改余弦参数,例如:

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)

如果您想用固定步骤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)
}

答案 2 :(得分:4)

另一个图书馆是PAcPie Char,你可以看看:

https://github.com/marshallino16/PacPieChart-Android

我还在写它,但至少,这是一个开始

答案 3 :(得分:2)

我认为你最好的朋友是aChartEngine 它易于使用,并提供各种图表来显示。

饼图示例:

enter image description here

答案 4 :(得分:1)

如果你想拥有最好的饼图,请执行以下操作: 1.打开build.gradle(模块:app)添加依赖implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'

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>
  1. 打开您的活动文件并粘贴以下代码:

    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
                    }
    }
    
  2. 它会给你下面的饼图; enter image description here

    图书馆也可以用于绘制条形图,线条图,水平条形图等

答案 5 :(得分:1)

打开build.gradle(module:app)并将库添加到依赖项中。

implementation 'com.github.lecho:hellocharts-library:1.5.8@aar'

接下来,您需要打开build.gradle(项目)并添加Jcenter,因为可以通过该库使用它。

allprojects {
repositories {
    google()
    jcenter()
}

}

现在通过单击立即同步来同步项目。

打开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>

这是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: $10"));
    pieData.add(new SliceValue(25, Color.GRAY).setLabel("Q2: $4"));
    pieData.add(new SliceValue(10, Color.RED).setLabel("Q3: $18"));
    pieData.add(new SliceValue(60, Color.MAGENTA).setLabel("Q4: $28"));

    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);
}
}

您可以看到https://www.codingdemos.com/android-pie-chart-tutorial/以获得更多描述。

答案 6 :(得分:0)

如果您不想使用任何第三方库,请尝试使用google示例表单。 它们提供了一个样本,用于在自定义绘图文档中绘制饼图。

Documentation and sample code can be found here