当前位置: 移动技术网 > IT编程>移动开发>Android > Android自定义View实现弹性小球效果

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

郭伯权儿子,启东天气,扬州工程建设信息网

照例先看效果图

自定义代码示例

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能带来一定的帮助,如果有疑问大家可以留言交流。谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网