当前位置: 首页 > 编程笔记 >

手把手教你用Android自定义饼状图

邢昊焜
2023-03-14
本文向大家介绍手把手教你用Android自定义饼状图,包括了手把手教你用Android自定义饼状图的使用技巧和注意事项,需要的朋友参考一下

照例先上效果图

通过该例子,你能学到什么:

     对Paint 深入理解,画绘制饼图,矩形,文字等

     加深对canvas的API的掌握,对自定义View掌握

下面我们分七步来完成一个简单的饼形图绘制过程。

1. 重新View的构造方法

public PieView(Context context) {
 this(context, null);
 }

 public PieView(Context context, AttributeSet attrs) {
 this(context, attrs, 0);
 }

 public PieView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 init();
 }

 private void init() {
 mPieColorList = new ArrayList<>();
 mPieValue = new ArrayList<>();
 mStringList = new ArrayList<>();
 mPaint = new Paint();
 mMaxString = "";
 mPaint.setColor(Color.BLACK);
 mPaint.setStrokeWidth(10);//画笔宽度
 mPaint.setAntiAlias(true);//抗锯齿
 }

2.绘制图形

/**
 * 绘制饼图
 *
 * @param canvas
 * @param amount
 */
 private void drawPie(Canvas canvas, int amount) {
 mPaint.setColor(mCurrentColor);
 mPaint.setStyle(Paint.Style.FILL);
 int angle = (int) (360f * amount / mMaxValue);
 Log.d("angle", "drawPie: " + angle);
 canvas.drawArc(oval, mStartAngle, angle, true, mPaint);
 mStartAngle += angle;
 }

 /**
 * 绘制矩形
 *
 * @param canvas
 */
 private void drawRect(Canvas canvas) {
 if (mCurrentIndex == 0) {
  rect = new RectF(mRectMarginLeft, mPadding, mRectMarginLeft + RECT_WIDTH, mPadding + RECT_WIDTH);
  canvas.drawRect(rect, mPaint);
 } else {
  rect = new RectF(mRectMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding, mRectMarginLeft + RECT_WIDTH, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + RECT_WIDTH);
  canvas.drawRect(rect, mPaint);
 }
 }

 /**
 * 绘画文字
 *
 * @param canvas
 * @param text
 */
 private void drawText(Canvas canvas, String text) {
 mPaint.setColor(TEXT_COLOR);
 if (mCurrentIndex == 0) {
  canvas.drawText(text, mTextMarginLeft, mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
 } else {
  canvas.drawText(text, mTextMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
 }
 }

3.Pie 实体类

public class Pie {
 public int PieColor;
 public int PieValue;
 public String PieString;

 public Pie(int pieValue, String pieString, int pieColor) {
 this.PieValue = pieValue;
 this.PieString = pieString;
 this.PieColor = pieColor;
 }
}

4.xml引用

 <aikaifa.canvas.widget.PieView
 android:layout_width="match_parent"
 android:layout_height="200dp"
 android:id="@+id/PieView" />

5.填充数据

public class MainActivity extends Activity {
 private ArrayList<Pie> pieArrayList = new ArrayList<>();
 private String[] arr = {"C#", "C", "C++", "JAVA", "JavaScript", "Object-C"};
 private int[] pre = {20, 30, 10, 10, 10, 20};
 private PieView pieView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 pieView = (PieView) findViewById(R.id.PieView);
 int[] pieColor = {getResources().getColor(R.color.blue), getResources().getColor(R.color.red), getResources().getColor(R.color.gray_dark),
  getResources().getColor(R.color.dark), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.black_alpha_light)};
 for (int i = 0; i < arr.length; i++) {
  Pie pie = new Pie(pre[i], arr[i], pieColor[i]);
  pieArrayList.add(pie);
 }
 pieView.SetPie(pieArrayList);
 }

}

6.完整的PieView

public class PieView extends View {

 private Paint mPaint;
 //饼图和矩形的距离
 private final int PIE_RECT_PADDING = getResources().getDimensionPixelSize(R.dimen.pie_rect_padding);
 //矩形的宽度
 private final int RECT_WIDTH = getResources().getDimensionPixelSize(R.dimen.rect_width);
 //矩形和文字的距离
 private final int RECT_TEXT_PADDING = getResources().getDimensionPixelSize(R.dimen.rect_text_padding);
 //文字的大小
 private final int TEXT_SIZE = getResources().getDimensionPixelSize(R.dimen.text_size);
 //文字的垂直距离
 private final int TEXT_VERTICAL_PADDING = getResources().getDimensionPixelSize(R.dimen.text_vertical_padding);
 //得到文字颜色
 private final int TEXT_COLOR = getResources().getColor(R.color.gray_dark);
 //文字和控件顶部的距离
 private float mPadding;
 //饼图的半径
 private int mPieRadios;
 //所有数值的总和
 private int mMaxValue;
 //饼图开始的角度
 private int mStartAngle;
 //文字的宽度
 private int mTextWidth;
 //控件半高
 private int mControlHalfHeight;
 //当前索引
 private int mCurrentIndex;
 //左边距
 private int mRectMarginLeft;
 private int mTextMarginLeft;
 //当前颜色
 private int mCurrentColor;
 //圆的范围
 private RectF oval;
 //最长的字符串
 private String mMaxString;

 private List<Integer> mPieColorList;
 private List<Integer> mPieValue;
 private List<String> mStringList;
 private ArrayList<Pie> mPieArrayList;

 private RectF rect;

 public PieView(Context context) {
 this(context, null);
 }

 public PieView(Context context, AttributeSet attrs) {
 this(context, attrs, 0);
 }

 public PieView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 init();
 }

 private void init() {
 mPieColorList = new ArrayList<>();
 mPieValue = new ArrayList<>();
 mStringList = new ArrayList<>();
 mPaint = new Paint();
 mMaxString = "";
 mPaint.setColor(Color.BLACK);
 mPaint.setStrokeWidth(10);//画笔宽度
 mPaint.setAntiAlias(true);//抗锯齿
 }

 @Override
 protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
 super.onSizeChanged(width, height, oldWidth, oldHeight);
 mTextWidth = (int) mPaint.measureText(mMaxString);
 mControlHalfHeight = height / 2;
 //饼图半径
 mPieRadios = mControlHalfHeight - 5;
 //控件内容宽度
 int contentWidth = mPieRadios * 2 + PIE_RECT_PADDING + RECT_WIDTH + RECT_TEXT_PADDING + mTextWidth;
 //内容的左边距
 int contentMarginLeft = (width - contentWidth) / 2;
 //矩形的左边距
 mRectMarginLeft = contentMarginLeft + mPieRadios * 2 + PIE_RECT_PADDING;
 //文字的左边距
 mTextMarginLeft = mRectMarginLeft + RECT_WIDTH + RECT_TEXT_PADDING;
 //文字和控件顶部的距离
 mPadding = height / mPieArrayList.size() * 0.8f;
 oval = new RectF(contentMarginLeft, mControlHalfHeight - mPieRadios,
  contentMarginLeft + mPieRadios * 2, mControlHalfHeight + mPieRadios);
 }

 /**
 * @param pieArrayList
 */
 public void SetPie(ArrayList<Pie> pieArrayList) {
 mPieArrayList = pieArrayList;
 for (Pie mPie : mPieArrayList) {
  mPieColorList.add(mPie.PieColor);
  mPieValue.add(mPie.PieValue);
  mStringList.add(mPie.PieString);
  if (mMaxString.length() > mPie.PieString.length())
  mMaxString = mPie.PieString;
 }

 //使用postInvalidate可以直接在主线程中更新界面
 postInvalidate();
 }

 @Override
 protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);

 mStartAngle = -90;
 mCurrentIndex = 0;
 mMaxValue = 100;
 mPaint.setStyle(Paint.Style.FILL);

 for (int i = 0; i < mPieValue.size(); i++) {
  mCurrentColor = mPieColorList.get(mCurrentIndex);
  Log.i("mCurrentColor", "onDraw: " + mCurrentColor);
  drawPie(canvas, mPieValue.get(mCurrentIndex));
  drawRect(canvas);
  drawText(canvas, mStringList.get(mCurrentIndex));
  mCurrentIndex++;
 }
 }

 /**
 * 绘制饼图
 *
 * @param canvas
 * @param amount
 */
 private void drawPie(Canvas canvas, int amount) {
 mPaint.setColor(mCurrentColor);
 mPaint.setStyle(Paint.Style.FILL);
 int angle = (int) (360f * amount / mMaxValue);
 Log.d("angle", "drawPie: " + angle);
 canvas.drawArc(oval, mStartAngle, angle, true, mPaint);
 mStartAngle += angle;
 }

 /**
 * 绘制矩形
 *
 * @param canvas
 */
 private void drawRect(Canvas canvas) {
 if (mCurrentIndex == 0) {
  rect = new RectF(mRectMarginLeft, mPadding, mRectMarginLeft + RECT_WIDTH, mPadding + RECT_WIDTH);
  canvas.drawRect(rect, mPaint);
 } else {
  rect = new RectF(mRectMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding, mRectMarginLeft + RECT_WIDTH, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + RECT_WIDTH);
  canvas.drawRect(rect, mPaint);
 }
 }

 /**
 * 绘画文字
 *
 * @param canvas
 * @param text
 */
 private void drawText(Canvas canvas, String text) {
 mPaint.setColor(TEXT_COLOR);
 if (mCurrentIndex == 0) {
  canvas.drawText(text, mTextMarginLeft, mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
 } else {
  canvas.drawText(text, mTextMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
 }
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
 if (event.getAction() == MotionEvent.ACTION_DOWN) {
  float x = event.getX();
  float y = event.getY();
  Log.e("",x+"-----------");
 }
 return true;
 }
}

7.其他文件

colors.xml

  <color name="dark">#0097a7</color>
  <color name="grey">#e0e0e0</color>
  <color name="gray_dark">#666666</color>
  <color name="black_alpha_light">#3c3f41</color>
  <color name="black_light">#383838</color>
  <color name="blue">#03a9f4</color>
  <color name="red">#ff4081</color>

dimens.xml

  <dimen name="fab_margin">16dp</dimen>
  <dimen name="pie_rect_padding">30dp</dimen>
  <dimen name="rect_text_padding">6dp</dimen>
  <dimen name="rect_width">15dp</dimen>
  <dimen name="text_size">18sp</dimen>
  <dimen name="text_vertical_padding">25dp</dimen>

总结

好了,这样一个简单的饼形图绘制就算完成了。希望这篇文章的内容对各位Android开发者们能有所帮助,如果有疑问大家可以留言交流。

 类似资料:
  • 很多朋友听过ChatGPT,但是不知道去哪里体验它,现在小牛手把手教你使用 ChatGPT。

  • 本文向大家介绍ASP.NET MVC3手把手教你构建Web,包括了ASP.NET MVC3手把手教你构建Web的使用技巧和注意事项,需要的朋友参考一下 开发工具:VS2010+MSSQL2005,需要使用MVC3.0 环境配置 第一步:到官方网站下载MVC3,提供了简体中文。先安装 AspNetMVC3ToolsUpdateSetup.exe,然后安装AspNetMVC3ToolsUpdateVS

  • 本文向大家介绍pycharm 配置svn的图文教程(手把手教你),包括了pycharm 配置svn的图文教程(手把手教你)的使用技巧和注意事项,需要的朋友参考一下 1.setting--version control--subversion,按照图中红色字体填入对应信息 2.配置中途遇到没找到svn.exe, 解决方法: 1.需要重新将svn安装一遍,点击modify 2. command lin

  • 本文向大家介绍手把手教你如何安装Pycharm(详细图文教程),包括了手把手教你如何安装Pycharm(详细图文教程)的使用技巧和注意事项,需要的朋友参考一下 本文介绍了手把手教你如何安装Pycharm,分享给大家,具体如下: 1、首先去Pycharm官网,或者直接输入网址:http://www.jetbrains.com/pycharm/download/#section=windows,下载P

  • 本文向大家介绍Android自定义控件实现饼状图,包括了Android自定义控件实现饼状图的使用技巧和注意事项,需要的朋友参考一下 本文实现一个如图所示的控件,包括两部分,左边的饼状图和中间的两个小方块,及右边的两行文字 实现起来比较简单,只是一些绘图API的调用 核心代码在onDraw函数里边,对静态控件进行绘制即可 Canvas 绘制文本时,使用FontMetrics对象,计算位置的坐标。参考

  • 本文向大家介绍手把手教学Android用jsoup解析html实例,包括了手把手教学Android用jsoup解析html实例的使用技巧和注意事项,需要的朋友参考一下 1.jsoup介绍 很多时候,我们需要从各种网页上面抓取数据,而jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作