Android中属性动画的使用

属性动画分为:透明,旋转,平移,缩放

1.透明的实现方式:

效果图:

   mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

        ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f, 1f);
        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是透明度alpha
        // 动画效果是:常规 - 全透明 - 常规
        animator.setDuration(5000);
        animator.start();

2.旋转的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "rotation", 0f, 360f);

        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是旋转alpha
        // 动画效果是:0 - 360
        animator.setDuration(5000);
        animator.start();

3.平移的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  float curTranslationX = mButton.getTranslationX();
        // 获得当前按钮的位置
        ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, 300,curTranslationX);


        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是X轴平移(在Y轴上平移同理,采用属性"translationY"
        // 动画效果是:从当前位置平移到 x=1500 再平移到初始位置
        animator.setDuration(5000);
        animator.start();

4.缩放的实现方式:

效果图:

mButton = (Button) findViewById(R.id.Button);
        // 创建动画作用对象:此处以Button为例

  ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "scaleX", 1f, 3f, 1f);
        // 表示的是:
        // 动画作用对象是mButton
        // 动画作用的对象的属性是X轴缩放
        // 动画效果是:放大到3倍,再缩小到初始大小
        animator.setDuration(5000);
        animator.start();

组合动画的使用:AnimatorSet

组合动画的基本操作:

  1. AnimatorSet.play(Animator anim) :播放当前动画
  2. AnimatorSet.after(long delay) :将现有动画延迟x毫秒后执行
  3. AnimatorSet.with(Animator anim) :将现有动画和传入的动画同时执行
  4. AnimatorSet.after(Animator anim) :将现有动画插入到传入的动画之后执行
  5. AnimatorSet.before(Animator anim) : 将现有动画插入到传入的动画之前执行

主要的代码实现步骤:

// 步骤1:设置需要组合的动画效果
ObjectAnimator translation = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, 300,curTranslationX);  
// 平移动画
ObjectAnimator rotate = ObjectAnimator.ofFloat(mButton, "rotation", 0f, 360f);  
// 旋转动画
ObjectAnimator alpha = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f, 1f);  
// 透明度动画

// 步骤2:创建组合动画的对象
AnimatorSet animSet = new AnimatorSet();  

// 步骤3:根据需求组合动画
animSet.play(translation).with(rotate).before(alpha);  
animSet.setDuration(5000);  

// 步骤4:启动动画
animSet.start();  

猜你喜欢

转载自blog.csdn.net/chen_md/article/details/80130726