关于自定义View

来源:互联网 发布:五子棋雾化器最佳数据 编辑:程序博客网 时间:2024/05/20 20:58

分享一个自己制作的Android自定义View。是一个圆环形状的反映真实进度的进度条,百分比的进度文字跟随已完成进度的圆弧转动。以下是效果图:


这个自定义View可以根据需要设定圆环的宽度和百分比文字的大小。

先说一下思路:这个View一共分为三部分:第一部分也就是灰色的圆环部分,代表未完成的进度;第二部分是蓝色的圆弧部分,代表已经完成的进度;第三部分是红色的百分比的数字百分比文本,显示当前确切的完成进度。

下面是View的编写思路:

①:定义三个画笔,分别画灰色圆环,蓝色圆弧,红色文字;
②:构造器中初始化数据,设置三个画笔的属性;
③:重写View的onMeasure方法,得到本View的宽度,高度,计算出中心点的坐标;
④:由于这个View是一个圆环形状,所以定义本View宽高中较小者的一半为整个圆环部分(包括圆环和文字)最外侧的半径,这样使用者可以任意指定本View的宽高,圆环可以恰好嵌入其中,不会超出空间,也不会浪费空间;
⑤:绘制圆环需要一个RectF对象,创建一个RectF对象,指定它的左上右下边界均距离View中心为整个圆环部分(包括圆环和文字)最外侧的半径减去圆环画笔宽度和文字高度较大者的一半,这样,整个圆环部分(包括圆环和文字)的边界恰好会与View的边界重合;
⑥:绘制紧贴着圆环的文字,需要一个Path对象来指定文字的路径。给这个Path对象添加一小段圆弧的轨迹,然后在圆弧上面绘制文字。这段圆弧也需要一个RectF对象,但是这个RectF要比上一个RectF小一些,来保证文字恰好在圆环轨迹上;
⑦:然后是最关键的重绘部分,重写onDraw方法。首先画出灰色圆环,这个比较简单,它不需要随进度变化而变化,只是一个圆环;
⑧:其次画出蓝色的圆弧。设定圆弧开始的角度是-90度,也就是圆环顶部。扫过的角度是当前百分比乘以360度一整圈的角度,并且随着progress增加而不断增加,产生动画的效果;
⑨:最难的部分,画文字。在路径上面画文字并不难,但是要精确确定文字的位置,使文字的中央恰好处于蓝色进度条的最前端。在这里我使用了Paint的一个方法:getTextWidths,这个方法可以根据当前需要绘制的文字,返回所有单个字符的宽度组成的一个float型的数组,然后根据这个数组可以得到要绘制文字所占的宽度,进而可以得到需要的Path对象需要的圆弧轨迹的长度,然后根据圆弧长度,得到圆弧角度(width = sweepAngle * 2 * π * R / 360 →sweepAngle = width * 360 / 2 / π / R),然后就可以用这个Path对象去画文字了。
⑩:这里我们给View添加了 一个方法,setProgress,参数为int型的进度,这样外界使用者就可以根据实际进度来指定View的进度来显示当前实际工作完成的百分比。

下面是代码View代码:

[java] view plain copy
  1. public class CircleNumberProgress extends View {  
  2.   
  3.     /** 进度条画笔的宽度(dp) */  
  4.     private int paintProgressWidth = 3;  
  5.   
  6.     /** 文字百分比的字体大小(sp) */  
  7.     private int paintTextSize = 20;  
  8.   
  9.     /** 未完成进度条的颜色 */  
  10.     private int paintUndoneColor = 0xffaaaaaa;  
  11.   
  12.     /** 已完成进度条的颜色 */  
  13.     private int paintDoneColor = 0xff67aae4;  
  14.   
  15.     /** 百分比文字的颜色 */  
  16.     private int paintTextColor = 0xffff0077;  
  17.   
  18.     /** 设置进度条画笔的宽度(px) */  
  19.     private int paintProgressWidthPx;  
  20.   
  21.     /** 文字画笔的尺寸(px) */  
  22.     private int paintTextSizePx;  
  23.     /** Context上下文环境 */  
  24.     private Context context;  
  25.   
  26.     /** 调用者设置的进程 0 - 100 */  
  27.     private int progress;  
  28.   
  29.     /** 画未完成进度圆弧的画笔 */  
  30.     private Paint paintUndone = new Paint();  
  31.   
  32.     /** 画已经完成进度条的画笔 */  
  33.     private Paint paintDone = new Paint();  
  34.   
  35.     /** 画文字的画笔 */  
  36.     private Paint paintText = new Paint();  
  37.   
  38.     /** 包围进度条圆弧的矩形 */  
  39.     private RectF rectF = new RectF();  
  40.   
  41.     /** 包围文字所在路径圆弧的矩形,比上一个矩形略小 */  
  42.     private RectF rectF2 = new RectF();  
  43.   
  44.     /** 进度文字所在的路径 */  
  45.     private Path path = new Path();  
  46.   
  47.     /** 文字所在路径圆弧的半径 */  
  48.     private int radiusText;  
  49.   
  50.     /** 是否进行过了测量 */  
  51.     private boolean isMeasured = false;  
  52.   
  53.     public CircleNumberProgress(Context context, AttributeSet attrs) {  
  54.         super(context, attrs);  
  55.         this.context = context;  
  56.         // 构造器中初始化数据  
  57.         initData();  
  58.     }  
  59.   
  60.     /** 初始化数据 */  
  61.     private void initData() {  
  62.   
  63.         // 设置进度条画笔的宽度  
  64.         paintProgressWidthPx = Utils.dip2px(context, paintProgressWidth);  
  65.   
  66.         // 设置文字画笔的尺寸(px)  
  67.         paintTextSizePx = Utils.sp2px(context, paintTextSize);  
  68.   
  69.         // 未完成进度圆环的画笔的属性  
  70.         paintUndone.setColor(paintUndoneColor);  
  71.         paintUndone.setStrokeWidth(paintProgressWidthPx);  
  72.         paintUndone.setAntiAlias(true);  
  73.         paintUndone.setStyle(Paint.Style.STROKE);  
  74.   
  75.         // 已经完成进度条的画笔的属性  
  76.         paintDone.setColor(paintDoneColor);  
  77.         paintDone.setStrokeWidth(paintProgressWidthPx);  
  78.         paintDone.setAntiAlias(true);  
  79.         paintDone.setStyle(Paint.Style.STROKE);  
  80.   
  81.         // 文字的画笔的属性  
  82.         paintText.setColor(paintTextColor);  
  83.         paintText.setTextSize(paintTextSizePx);  
  84.         paintText.setAntiAlias(true);  
  85.         paintText.setStyle(Paint.Style.STROKE);  
  86.         paintText.setTypeface(Typeface.DEFAULT_BOLD);  
  87.   
  88.     }  
  89.   
  90.     @Override  
  91.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  92.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  93.         if (!isMeasured) {  
  94.             getWidthAndHeight();  
  95.             isMeasured = true;  
  96.         }  
  97.     }  
  98.   
  99.     /** 得到视图等的高度宽度尺寸数据 */  
  100.     private void getWidthAndHeight() {  
  101.   
  102.         // 得到自定义视图的高度  
  103.         int viewHeight;  
  104.   
  105.         // 得到自定义视图的宽度  
  106.         int viewWidth;  
  107.   
  108.         // 得到自定义视图的X轴中心点  
  109.         int viewCenterX;  
  110.   
  111.         // 得到自定义视图的Y轴中心点  
  112.         int viewCenterY;  
  113.   
  114.         viewHeight = getMeasuredHeight();  
  115.         viewWidth = getMeasuredWidth();  
  116.         viewCenterX = viewWidth / 2;  
  117.         viewCenterY = viewHeight / 2;  
  118.   
  119.         // 取本View长宽较小者的一半为整个圆环部分(包括圆环和文字)最外侧的半径  
  120.         int minLenth = viewHeight > viewWidth ? viewWidth / 2 : viewHeight / 2;  
  121.   
  122.         // 比较文字高度和圆环宽度,如果文字高度较大,那么文字将突破圆环,否则,圆环会把文字包裹在内部  
  123.         Rect rect = new Rect();  
  124.         paintText.getTextBounds("100%"0"100%".length(), rect);  
  125.         int textHeight = rect.height();  
  126.   
  127.         // 得到圆环的中间半径(外径和内径平均值)  
  128.         int radiusArc = minLenth - (paintProgressWidthPx > textHeight ? paintProgressWidthPx / 2 : textHeight / 2);  
  129.         rectF.left = viewCenterX - radiusArc;  
  130.         rectF.top = viewCenterY - radiusArc;  
  131.         rectF.right = viewCenterX + radiusArc;  
  132.         rectF.bottom = viewCenterY + radiusArc;  
  133.   
  134.         // 文字所依赖路径圆弧的半径  
  135.         radiusText = radiusArc - textHeight / 2;  
  136.         rectF2.left = viewCenterX - radiusText;  
  137.         rectF2.top = viewCenterY - radiusText;  
  138.         rectF2.right = viewCenterX + radiusText;  
  139.         rectF2.bottom = viewCenterY + radiusText;  
  140.   
  141.     }  
  142.   
  143.     @Override  
  144.     protected void onDraw(Canvas canvas) {  
  145.         super.onDraw(canvas);  
  146.   
  147.         // 画未完成进度的圆环  
  148.         canvas.drawArc(rectF, 0360false, paintUndone);  
  149.   
  150.         // 画已经完成进度的圆弧 从-90度开始,即从圆环顶部开始  
  151.         canvas.drawArc(rectF, -90, progress / 100.0f * 360false, paintDone);  
  152.   
  153.         // 为文字所在路径添加一段圆弧轨迹,进度为0%-9%时应该最短,进度为10%-99%时应该边长,进度为100%时应该最长  
  154.         // 这样才能保证文字和圆弧的进度一致,不会出现超前或者滞后的情况  
  155.   
  156.         // 要画的文字  
  157.         String text = progress + "%";  
  158.   
  159.         // 存储字符所有字符所占宽度的数组  
  160.         float[] widths = new float[text.length()];  
  161.   
  162.         // 得到所有字符所占的宽度  
  163.         paintText.getTextWidths(text, 0, text.length(), widths);  
  164.   
  165.         // 所有字符所占宽度之和  
  166.         float textWidth = 0;  
  167.         for (float f : widths) {  
  168.             textWidth += f;  
  169.         }  
  170.   
  171.         // 根据长度得到路径对应的扫过的角度  
  172.         // width = sweepAngle * 2 * π * R / 360 ; sweepAngle = width * 360 / 2 /  
  173.         // π / R  
  174.         float sweepAngle = (float) (textWidth * 360 / 2 / Math.PI / radiusText);  
  175.   
  176.         // 添加路径  
  177.         path.addArc(rectF2, progress * 3.6f - 90.0f - sweepAngle / 2.0f, sweepAngle);  
  178.   
  179.         // 绘制进度的文字  
  180.         canvas.drawTextOnPath(text, path, 00, paintText);  
  181.   
  182.         // 重置路径  
  183.         path.reset();  
  184.     }  
  185.   
  186.     /** 
  187.      * @param progress 外部传进来的当前进度,强制重绘 
  188.      */  
  189.     public void setProgress(int progress) {  
  190.         this.progress = progress;  
  191.         invalidate();  
  192.     }  
  193. }  



调用者Activity代码:

[java] view plain copy
  1. public class NumberProgressBarActivity extends Activity {  
  2.   
  3.     /** handler消息标识 */  
  4.     protected static final int WHAT_INCREASE = 1;  
  5.   
  6.     /** 圆形带数字的进度条 */  
  7.     private CircleNumberProgress cnp_citcleNumberProgress;  
  8.   
  9.     /** 指定给进度条的进程 */  
  10.     private int progress;  
  11.   
  12.     private Handler handler = new Handler() {  
  13.         public void handleMessage(android.os.Message msg) {  
  14.             progress++;  
  15.             cnp_citcleNumberProgress.setProgress(progress);  
  16.             handler.sendEmptyMessageDelayed(WHAT_INCREASE, getRadomNumber(50300));  
  17.             if (progress >= 100) {  
  18.                 handler.removeMessages(WHAT_INCREASE);  
  19.             }  
  20.         }  
  21.   
  22.     };  
  23.   
  24.     @Override  
  25.     protected void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.activity_number_progress_bar);  
  28.         cnp_citcleNumberProgress = (CircleNumberProgress) findViewById(R.id.cnp_citcleNumberProgress);  
  29.         Button btn_numberProgressBar = (Button) findViewById(R.id.btn_numberProgressBar);  
  30.         btn_numberProgressBar.setOnClickListener(new View.OnClickListener() {  
  31.             @Override  
  32.             public void onClick(View v) {  
  33.                 increase();  
  34.             }  
  35.         });  
  36.     }  
  37.   
  38.     private void increase() {  
  39.         progress = 0;  
  40.         handler.removeMessages(WHAT_INCREASE);  
  41.         handler.sendEmptyMessage(WHAT_INCREASE);  
  42.     }  
  43.   
  44.     /** 
  45.      * 得到两个整数之间的一个随机数 
  46.      * 
  47.      * @param start 较小的数 
  48.      * @param end   较大的数 
  49.      * @return 随机整数 
  50.      */  
  51.     public int getRadomNumber(int start, int end) {  
  52.         return (int) (start + Math.random() * (end - start));  
  53.     }  
  54. }  

布局:

[html] view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.               android:layout_width="match_parent"  
  3.               android:layout_height="match_parent"  
  4.               android:orientation="vertical">  
  5.   
  6.     <com.example.viewdemo.view.CircleNumberProgress  
  7.         android:id="@+id/cnp_citcleNumberProgress"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="300dp"  
  10.         android:layout_margin="20dp"  
  11.         android:background="#33897500"/>  
  12.   
  13.     <Button  
  14.         android:id="@+id/btn_numberProgressBar"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="开始"/>  
  18.   
  19. </LinearLayout>  

还有几个方法是dp,px,sp相互转换的也一并贴出来:

[java] view plain copy
  1. /** 
  2.  * 将px值转换为dip或dp值,保证尺寸大小不变 
  3.  */  
  4. public static int px2dip(Context context, float pxValue) {  
  5.     final float scale = context.getResources().getDisplayMetrics().density;  
  6.     return (int) (pxValue / scale + 0.5f);  
  7. }  
  8.   
  9. /** 
  10.  * 将dip或dp值转换为px值,保证尺寸大小不变 
  11.  */  
  12. public static int dip2px(Context context, float dipValue) {  
  13.     final float scale = context.getResources().getDisplayMetrics().density;  
  14.     return (int) (dipValue * scale + 0.5f);  
  15. }  
  16.   
  17. /** 
  18.  * 将px值转换为sp值,保证文字大小不变 
  19.  */  
  20. public static int px2sp(Context context, float pxValue) {  
  21.     final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
  22.     return (int) (pxValue / fontScale + 0.5f);  
  23. }  
  24.   
  25. /** 
  26.  * 将sp值转换为px值,保证文字大小不变 
  27.  */  
  28. public static int sp2px(Context context, float spValue) {  
  29.     final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
  30.     return (int) (spValue * fontScale + 0.5f);  
  31. }