一看就喜欢的loading动画效果Android分析实现

2019-12-10 19:13:34于丽

接下来再来看叶子部分:
首先根据效果情况基本确定出 曲线函数,标准函数方程为:y = A(wx+Q)+h,其中w影响周期,A影响振幅 ,周期T= 2 * Math.PI/w;
根据效果可以看出,周期大致为总进度长度,所以确定w=(float) ((float) 2 * Math.PI /mProgressWidth);

仔细观察效果,我们可以发现,叶子飘动的过程中振幅不是完全一致的,产生一种错落的效果,既然如此,我们给叶子定义一个Type,根据Type 确定不同的振幅;
我们创建一个叶子对象:

private class Leaf { 
 
   // 在绘制部分的位置 
   float x, y; 
   // 控制叶子飘动的幅度 
   StartType type; 
   // 旋转角度 
   int rotateAngle; 
   // 旋转方向--0代表顺时针,1代表逆时针 
   int rotateDirection; 
   // 起始时间(ms) 
   long startTime; 
 } 

类型采用枚举进行定义,其实就是用来区分不同的振幅:

private enum StartType { 
  LITTLE, MIDDLE, BIG 
} 

创建一个LeafFactory类用于创建一个或多个叶子信息:

private class LeafFactory { 
  private static final int MAX_LEAFS = 6; 
  Random random = new Random(); 
 
  // 生成一个叶子信息 
  public Leaf generateLeaf() { 
    Leaf leaf = new Leaf(); 
    int randomType = random.nextInt(3); 
    // 随时类型- 随机振幅 
    StartType type = StartType.MIDDLE; 
    switch (randomType) { 
      case 0: 
        break; 
      case 1: 
        type = StartType.LITTLE; 
        break; 
      case 2: 
        type = StartType.BIG; 
        break; 
      default: 
        break; 
    } 
    leaf.type = type; 
    // 随机起始的旋转角度 
    leaf.rotateAngle = random.nextInt(360); 
    // 随机旋转方向(顺时针或逆时针) 
    leaf.rotateDirection = random.nextInt(2); 
    // 为了产生交错的感觉,让开始的时间有一定的随机性 
    mAddTime += random.nextInt((int) (LEAF_FLOAT_TIME * 1.5)); 
    leaf.startTime = System.currentTimeMillis() + mAddTime; 
    return leaf; 
  } 
 
  // 根据最大叶子数产生叶子信息 
  public List<Leaf> generateLeafs() { 
    return generateLeafs(MAX_LEAFS); 
  } 
 
  // 根据传入的叶子数量产生叶子信息 
  public List<Leaf> generateLeafs(int leafSize) { 
    List<Leaf> leafs = new LinkedList<Leaf>(); 
    for (int i = 0; i < leafSize; i++) { 
      leafs.add(generateLeaf()); 
    } 
    return leafs; 
  } 
}