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

Android自定义View实现弹性小球效果

程序员文章站 2024-03-06 10:14:31
照例先看效果图 自定义代码示例 public class bezierview extends view { paint paint;//画笔...

照例先看效果图

Android自定义View实现弹性小球效果

自定义代码示例

public class bezierview extends view {

 paint paint;//画笔
 path path;//路径

 int radius = 50;//圆的半径
 int time = 100;//计数时长

 int index;
 int offsetindex;
 float viewx, viewy;//图形中心点坐标

 float width;//屏幕宽度
 float partwidth;//屏幕宽度的1/4
 int paddingleft, paddingright;//图形内边距
 float x1, y1, x2, y2, x3, y3, x4, y4;//圆形左上右下四个点

 float x12, y12, x23, y23, x34, y34, x41, y41;//圆形左上右下四个点之间的渐变点

 public bezierview(context context) {
  this(context, null);
 }

 public bezierview(context context, attributeset attrs) {
  this(context, attrs, 0);
 }

 public bezierview(context context, attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);

  paint = new paint();
  paint.setcolor(resourcescompat.getcolor(getresources(), r.color.colorprimary, null));
  paint.setantialias(true);
 }


 @override
 protected void ondraw(canvas canvas) {
  paddingleft = getpaddingleft();
  paddingright = getpaddingright();
  width = getwidth() - paddingleft - paddingright;
  partwidth = width / 4;

  path = new path();
  path.moveto(x1, y1);
  path.cubicto(x1, y1, x12, y12, x2, y2);
  path.cubicto(x2, y2, x23, y23, x3, y3);
  path.cubicto(x3, y3, x34, y34, x4, y4);
  path.cubicto(x4, y4, x41, y41, x1, y1);
  canvas.drawpath(path, paint);

  move();
 }


 public void move() {
  new timer().schedule(new timertask() {
   @override
   public void run() {
    if (index < time - 1) {
     index++;
     viewx = width / time * index + paddingleft;
     viewy = 400;

     x1 = viewx - radius;
     x2 = viewx;
     x3 = viewx + radius;
     x4 = viewx;

     y1 = viewy;
     y2 = viewy - radius;
     y3 = viewy;
     y4 = viewy + radius;

     offsetindex = index % (time / 4) + 1;

     //根据图形移动到的区域进行曲线变化
     float position = (viewx - paddingleft) / partwidth;

     //右边半圆
     if (position >= 0 && position < 1) {
      x3 = viewx + radius + radius / (time / 4) * offsetindex;
     } else if (position >= 1 && position < 2) {
      x3 = viewx + radius + radius;
     } else if (position >= 2 && position < 3) {
      x3 = viewx + radius + radius - radius / (time / 4) * offsetindex;
     } else {
      x3 = viewx + radius;
     }
     x23 = x34 = x3;
     y12 = y23 = y2;

     //左边半圆
     if (position >= 1 && position < 2) {
      x1 = viewx - radius - radius / (time / 4) * offsetindex;
     } else if (position >= 2 && position < 3) {
      x1 = viewx - radius - radius;
     } else if (position >= 3) {
      x1 = viewx - radius - radius + radius / (time / 4) * offsetindex;
     } else {
      x1 = viewx - radius;
     }
     x12 = x41 = x1;
     y34 = y41 = y4;

     postinvalidate();
    } else {
     cancel();
    }
   }
  }, 0, 5000);
 }

}

总结

以上就是android自定义view实现弹性小球效果的全部内容,希望对大家开发android能带来一定的帮助,如果有疑问大家可以留言交流。谢谢大家对的支持。