欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android自定义View实现圆环进度条

程序员文章站 2022-04-09 17:08:55
本文实例为大家分享了android自定义view实现圆环进度条的具体代码,供大家参考,具体内容如下效果展示动画效果view实现1.底层圆环是灰色背景2.上层圆环是红色背景3.使用动画画一条弧线view...

本文实例为大家分享了android自定义view实现圆环进度条的具体代码,供大家参考,具体内容如下

效果展示

动画效果

Android自定义View实现圆环进度条

view实现

1.底层圆环是灰色背景
2.上层圆环是红色背景
3.使用动画画一条弧线

view

/**
 * 圆环进度条
 */
public class roundprogressbar extends view {
 //绘制矩形区域
 private rectf rectf;
 //起始角度
 private float startangle;
 //扫过角度
 private float sweepangle;
 //画笔
 private paint paint;
 //默认控件大小
 private int defoutsize;
 //默认线条宽度
 private int defoutline;
 private int strokewidth;

 private pointf pointf = new pointf();


 public roundprogressbar(context context) {
  super(context);
  initdata();
 }

 public roundprogressbar(context context, attributeset attrs) {
  super(context, attrs);
  initdata();
 }

 /**
  * 参数初始化
  */
 private void initdata() {
  startangle = 0;
  sweepangle = 0;
  defoutsize = 400;
  defoutline = 20;
  strokewidth = 20;

  rectf = new rectf();

  //抗锯齿画笔
  paint = new paint(paint.anti_alias_flag);
  paint.setcolor(color.gray);
  paint.setstrokewidth(defoutline);
  //笔帽样式
  paint.setstrokecap(paint.cap.round);
  paint.setstyle(paint.style.stroke);
 }

 /**
  * xml -----> 提供可绘制位置
  *
  * @param widthmeasurespec 宽
  * @param heightmeasurespec 高
  */
 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  super.onmeasure(widthmeasurespec, heightmeasurespec);
  setmeasureddimension(defoutsize, defoutsize);
 }

 /**
  * 当大小时改变回调
  *
  * @param w
  * @param h
  * @param oldw
  * @param oldh
  */
 @override
 protected void onsizechanged(int w, int h, int oldw, int oldh) {
  super.onsizechanged(w, h, oldw, oldh);

  pointf.x = w >> 1;
  pointf.y = h >> 1;

  rectf.top = strokewidth >> 1;
  rectf.bottom = h - (strokewidth >> 1);
  rectf.left = strokewidth >> 1;
  rectf.right = w - (strokewidth >> 1);

 }

 /**
  * 绘制
  *
  * @param canvas
  */
 @override
 protected void ondraw(canvas canvas) {
  super.ondraw(canvas);

  //画布旋转
  paint.setcolor(color.gray);
  canvas.rotate(135, pointf.x, pointf.y);
  //绘制圆环
  canvas.drawarc(rectf, startangle, 270, false, paint);

  paint.setcolor(color.red);
  canvas.drawarc(rectf, startangle, sweepangle, false, paint);

 }

 public void setprogress(float index) {
 //防止数值越界
  if (index > 1 || index < 0) {
   return;
  }
  valueanimator valueanimator = valueanimator.offloat(0, index);
  valueanimator.setduration(3000);
  valueanimator.setinterpolator(new decelerateinterpolator());
  valueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() {
   @override
   public void onanimationupdate(valueanimator animation) {
    sweepangle = (float) animation.getanimatedvalue() * 270;
    //重写绘制
    invalidate();
   }
  });
  valueanimator.start();

 }
}

最后在activity中使用setprogress方法赋值进度条的进度来实现效果

progressview.setprogress(0.8f);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。