Android开源图表之树状图和饼状图的官方示例的整理

壮心未与年俱老,死去犹能作鬼雄。这篇文章主要讲述Android开源图表之树状图和饼状图的官方示例的整理相关的知识,希望能为你提供帮助。
最近由于工作需要,所以就在github上搜了下关于chart的三方框架
官方地址https://github.com/PhilJay/MPandroidChart
由于工作需要我这里整理了一份Eclipse版本的类库.(有需要要的留下邮箱)

Android开源图表之树状图和饼状图的官方示例的整理

文章图片

这就是Code中的效果(树状图)

1 public class BarChartActivity extends Activity implements OnChartValueSelectedListener{ 2 3private BarChart mChart; 4private Typeface mTfLight; 5 6@Override 7protected void onCreate(Bundle savedInstanceState) { 8// TODO Auto-generated method stub 9super.onCreate(savedInstanceState); 10setContentView(R.layout.activity_barchart); 11 12mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"); 13 14mChart = (BarChart) findViewById(R.id.chart1); 15mChart.setOnChartValueSelectedListener(this); 16 17mChart.setDrawBarShadow(false); //--绘制当前展示的内容顶部阴影 18mChart.setDrawValueAboveBar(true); //--绘制的图形都在bar顶部 19 20mChart.setDescription(""); 21 22// if more than 60 entries are displayed in the chart, no values will be 23// drawn 24mChart.setMaxVisibleValueCount(80); //Y方向的最大值. 25 26// scaling can now only be done on x- and y-axis separately 27mChart.setPinchZoom(false); //--双指缩放. 28 29mChart.setDrawGridBackground(false); //--绘制中心内容区域背景色. 30// mChart.setDrawYLabels(false); 31 32XAxis xAxis = mChart.getXAxis(); 33xAxis.setPosition(XAxisPosition.BOTTOM); 34xAxis.setTypeface(mTfLight); 35xAxis.setDrawGridLines(false); //--是否绘制竖直分割线. 36xAxis.setGranularity(1f); // only intervals of 1 day底部label的分割间隙 37xAxis.setLabelCount(5); //--对应的当前绘制在底部的label数 38xAxis.setValueFormatter(new DayAxisValueFormatter(mChart)); 39 40AxisValueFormatter custom = new MyAxisValueFormatter(); 41 42YAxis leftAxis = mChart.getAxisLeft(); 43leftAxis.setTypeface(mTfLight); 44leftAxis.setDrawGridLines(false); //-绘制水平分割线,按照当前Y方向的label点为起始点 45leftAxis.setLabelCount(8, false); //--绘制Y方向(应该)被显示的数量,第二个参数表示label是否是精准变化,还是近似变化 46leftAxis.setValueFormatter(custom); 47leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART); //Y方向文字的位置,在线外侧.(默认在外侧) 48leftAxis.setSpaceTop(15f); //分割线的间距百分比. 49leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)Y方向的起始值. 50 51YAxis rightAxis = mChart.getAxisRight(); 52rightAxis.setDrawGridLines(true); //-绘制水平分割线,按照当前Y方向的label点为起始点 53rightAxis.setTypeface(mTfLight); 54rightAxis.setLabelCount(8, false); 55rightAxis.setValueFormatter(custom); 56rightAxis.setSpaceTop(15f); 57rightAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true) 58 59Legend l = mChart.getLegend(); 60l.setForm(LegendForm.SQUARE); //--设置legend的形状. 61l.setPosition(LegendPosition.BELOW_CHART_LEFT); //--设置legend的位置. 62l.setFormSize(12f); //--设置legend的大小 63l.setTextSize(12f); //--设置legend上的文字大小 64 //l.setXEntrySpace(100f); 65l.setYOffset(30f); 66// l.setExtra(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", 67// "def", "ghj", "ikl", "mno" }); 68// l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", 69// "def", "ghj", "ikl", "mno" }); 70mChart.animateY(3000); 71mChart.setPinchZoom(true); 72setData(12, 80); 73} 74 75private void setData(int count, float range) { 76 77float start = 0f; 78 79mChart.getXAxis().setAxisMinValue(start); 80mChart.getXAxis().setAxisMaxValue(start + count + 2); 81 82ArrayList< BarEntry> yVals1 = new ArrayList< BarEntry> (); 83 84for (int i = (int) start; i < start + count + 1; i++) { 85float mult = (range + 1); 86float val = (float) (Math.random() * mult); 87BarEntry barEntry = new BarEntry(i + 1f, val); 88 89yVals1.add(barEntry); 90} 91 92BarDataSet set1; 93 94if (mChart.getData() != null & & 95mChart.getData().getDataSetCount() > 0) { 96set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0); 97set1.setValues(yVals1); 98mChart.getData().notifyDataChanged(); 99mChart.notifyDataSetChanged(); 100} else { 101set1 = new BarDataSet(yVals1, "The year 2017"); 102set1.setBarBorderWidth(1); 103set1.setColors(ColorTemplate.MATERIAL_COLORS); 104 105ArrayList< IBarDataSet> dataSets = new ArrayList< IBarDataSet> (); 106dataSets.add(set1); 107 108BarData data = https://www.songbingjia.com/android/new BarData(dataSets); 109data.setValueTextSize(10f); 110data.setValueTypeface(mTfLight); 111 112data.setBarWidth(0.8f); //--设置bar的宽度 ,取值(0-1). 113 114mChart.setData(data); 115} 116} 117 118protected RectF mOnValueSelectedRectF = new RectF(); 119 120@Override 121public void onValueSelected(Entry e, Highlight h) { 122// TODO Auto-generated method stub 123if (e == null) 124return; 125 126RectF bounds = mOnValueSelectedRectF; 127mChart.getBarBounds((BarEntry) e, bounds); 128MPPointF position = mChart.getPosition(e, AxisDependency.LEFT); 129 130Log.i("bounds", bounds.toString()); 131Log.i("position", position.toString()); 132 133Log.i("x-index", 134"low: " + mChart.getLowestVisibleX() + ", high: " 135+ mChart.getHighestVisibleX()); 136 137MPPointF.recycleInstance(position); 138} 139 140@Override 141public void onNothingSelected() { 142// TODO Auto-generated method stub 143 144} 145 146@Override 147public boolean onCreateOptionsMenu(Menu menu) { 148getMenuInflater().inflate(R.menu.bar, menu); 149return true; 150} 151 152@Override 153public boolean onOptionsItemSelected(MenuItem item) { 154 155switch (item.getItemId()) { 156case R.id.actionToggleValues: { 157for (IDataSet set : mChart.getData().getDataSets()) 158set.setDrawValues(!set.isDrawValuesEnabled()); 159 160mChart.invalidate(); 161break; 162} 163case R.id.actionToggleHighlight: { 164if (mChart.getData() != null) { 165mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled()); 166mChart.invalidate(); 167} 168break; 169} 170case R.id.actionTogglePinch: { 171if (mChart.isPinchZoomEnabled()) 172mChart.setPinchZoom(false); 173else 174mChart.setPinchZoom(true); 175 176mChart.invalidate(); 177break; 178} 179case R.id.actionToggleAutoScaleMinMax: { 180mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled()); 181mChart.notifyDataSetChanged(); 182break; 183} 184case R.id.actionToggleBarBorders: { 185for (IBarDataSet set : mChart.getData().getDataSets()) 186((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f); 187 188mChart.invalidate(); 189break; 190} 191case R.id.animateX: { 192mChart.animateX(3000); 193break; 194} 195case R.id.animateY: { 196mChart.animateY(3000); 197break; 198} 199case R.id.animateXY: { 200 201mChart.animateXY(3000, 3000); 202break; 203} 204case R.id.actionSave: { 205if (mChart.saveToGallery("title" + System.currentTimeMillis(), 50)) { 206Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!", 207Toast.LENGTH_SHORT).show(); 208} else 209Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT) 210.show(); 211break; 212} 213} 214return true; 215}

 
【Android开源图表之树状图和饼状图的官方示例的整理】上述代码中关键点已经加入注释,纯属自己个个人研究理解,那里理解不对的地方,回应告知
说完树状图紧接着就是饼状图我这里分别实现了两种,不过基本code都是一样的
Android开源图表之树状图和饼状图的官方示例的整理

文章图片

 
Android开源图表之树状图和饼状图的官方示例的整理

文章图片

 
不多说直接上代码:

1 public class PieChartActivity extends Activity implements OnChartValueSelectedListener { 2 3private PieChart mChart; 4private Typeface mTfRegular; 5private Typeface mTfLight; 6 7protected String[] mMonths = new String[] { 8"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec" 9}; 10 11protected String[] mParties = new String[] { 12"Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H", 13"Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P", 14"Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X", 15"Party Y", "Party Z" 16}; 17 18@Override 19protected void onCreate(Bundle savedInstanceState) { 20super.onCreate(savedInstanceState); 21setContentView(R.layout.activity_main); 22 23mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); 24mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"); 25 26mChart = (PieChart) findViewById(R.id.chart1); 27mChart.setUsePercentValues(true); 28mChart.setDescription("描述内容"); 29mChart.setDescriptionTextSize(20); 30 31mChart.setExtraOffsets(5, 5, 5, 5); 32 33mChart.setDragDecelerationFrictionCoef(0.95f); 34 35mChart.setCenterTextTypeface(mTfLight); 36mChart.setCenterText(generateCenterSpannableText()); //--设置中心点文字 37 38mChart.setDrawHoleEnabled(true); 39mChart.setHoleColor(Color.RED); 40 41mChart.setTransparentCircleColor(Color.BLUE); //--内圆边框色 42mChart.setTransparentCircleAlpha(110); //--内圆边框透明度 43 44mChart.setHoleRadius(58f); //--内院半径 45mChart.setTransparentCircleRadius(61f); //--内圆边框大小半径 46 47mChart.setDrawCenterText(true); 48 49mChart.setRotationAngle(0); //--绘制的开始位置 50// enable rotation of the chart by touch 51mChart.setRotationEnabled(true); //--允许旋转 52mChart.setHighlightPerTapEnabled(true); //---允许点击其中某个扇形区域. 53 54// add a selection listener 55mChart.setOnChartValueSelectedListener(this); 56 57setData(8, 100); 58 59mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad); 60 61Legend l = mChart.getLegend(); 62l.setPosition(LegendPosition.RIGHT_OF_CHART); 63l.setXEntrySpace(100f); 64l.setYEntrySpace(0f); 65l.setYOffset(0f); 66 67// entry label styling 68mChart.setEntryLabelColor(Color.RED); //--设置饼状图其中各个块上的文字颜色 69mChart.setEntryLabelTypeface(mTfRegular); //---设置字体 70mChart.setEntryLabelTextSize(24f); //--设置字体大小 71} 72 73private void setData(int count, float range) { 74 75float mult = range; 76 77ArrayList< PieEntry> entries = new ArrayList< PieEntry> (); 78 79// NOTE: The order of the entries when being added to the entries array determines their position around the center of 80// the chart. 81for (int i = 0; i < count ; i++) { 82entries.add(new PieEntry((float) ((Math.random() * mult) + mult / 5), mParties[i % mParties.length])); 83} 84 85 //PieEntry --参数说明:第一个参数代表半分比,第二个参数表示名字。 86 87PieDataSet dataSet = new PieDataSet(entries, "< 一张图> "); 88dataSet.setSliceSpace(6f); //--饼状图 89dataSet.setSelectionShift(15f); //--选中饼状图时,向外扩张的大小. 90 91// add a lot of colors 92 93ArrayList< Integer> colors = new ArrayList< Integer> (); 94 95for (int c : ColorTemplate.VORDIPLOM_COLORS) 96colors.add(c); 97 98for (int c : ColorTemplate.JOYFUL_COLORS) 99colors.add(c); 100 101for (int c : ColorTemplate.COLORFUL_COLORS) 102colors.add(c); 103 104for (int c : ColorTemplate.LIBERTY_COLORS) 105colors.add(c); 106 107for (int c : ColorTemplate.PASTEL_COLORS) 108colors.add(c); 109 110colors.add(ColorTemplate.getHoloBlue()); 111 112dataSet.setColors(colors); 113 114PieData data = https://www.songbingjia.com/android/new PieData(dataSet); 115data.setValueFormatter(new PercentFormatter()); 116data.setValueTextSize(20f); //--设置字体大小 117data.setValueTextColor(Color.RED); //--设置饼状图其中各个块上的百分比颜色 118data.setValueTypeface(mTfLight); //--设置字体 119mChart.setData(data); 120 121// undo all highlights 122mChart.highlightValues(null); 123 124mChart.invalidate(); 125} 126 127 128private SpannableString generateCenterSpannableText() { 129 130SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda"); 131s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0); 132s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0); 133s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0); 134s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0); 135s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0); 136s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0); 137return s; 138} 139 140@Override 141public boolean onCreateOptionsMenu(Menu menu) { 142getMenuInflater().inflate(R.menu.pie, menu); 143return true; 144} 145 146@Override 147public boolean onOptionsItemSelected(MenuItem item) { 148 149switch (item.getItemId()) { 150case R.id.actionToggleValues: { 151for (IDataSet< ?> set : mChart.getData().getDataSets()) 152set.setDrawValues(!set.isDrawValuesEnabled()); 153 154mChart.invalidate(); 155break; 156} 157case R.id.actionToggleHole: { 158if (mChart.isDrawHoleEnabled()) 159mChart.setDrawHoleEnabled(false); 160else 161mChart.setDrawHoleEnabled(true); 162mChart.invalidate(); 163break; 164} 165case R.id.actionDrawCenter: { 166if (mChart.isDrawCenterTextEnabled()) 167mChart.setDrawCenterText(false); 168else 169mChart.setDrawCenterText(true); 170mChart.invalidate(); 171break; 172} 173case R.id.actionToggleXVals: { 174 175mChart.setDrawEntryLabels(!mChart.isDrawEntryLabelsEnabled()); 176mChart.invalidate(); 177break; 178} 179case R.id.actionSave: { 180// mChart.saveToGallery("title"+System.currentTimeMillis()); 181mChart.saveToPath("title" + System.currentTimeMillis(), ""); 182break; 183} 184case R.id.actionTogglePercent: 185mChart.setUsePercentValues(!mChart.isUsePercentValuesEnabled()); 186mChart.invalidate(); 187break; 188case R.id.animateX: { 189mChart.animateX(1400); 190break; 191} 192case R.id.animateY: { 193mChart.animateY(1400); 194break; 195} 196case R.id.animateXY: { 197mChart.animateXY(1400, 1400); 198break; 199} 200case R.id.actionToggleSpin: { 201mChart.spin(1000, mChart.getRotationAngle(), mChart.getRotationAngle() + 360, Easing.EasingOption 202.EaseInCubic); 203break; 204} 205} 206return true; 207} 208 209 210 211@Override 212public void onValueSelected(Entry e, Highlight h) { 213// TODO Auto-generated method stub 214if (e == null) 215return; 216Log.i("VAL SELECTED", 217"Value: " + e.getY() + ", index: " + h.getX() 218+ ", DataSet index: " + h.getDataSetIndex()); 219 220} 221 222 223@Override 224public void onNothingSelected() { 225// TODO Auto-generated method stub 226Log.i("PieChart", "nothing selected"); 227} 228 229 }

 

 

    推荐阅读