---
title: "Android动画开发"
author: "chanshui"
date: "2012-11-08T00:13:26Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2012-11-08T00:13:26Z"
id: 1719928
url: "https://chanshui.iteye.com/blog/1719928"
---

本文主要研究Android中的三种动画，第一种是单个View的各种动画效果，第二种是两个Activity切换时的动画效果，第三种是类似于Gif的Frame By Frame动画效果，其中View的各种动画包括在xml文件中定义和代码中定义两种方式。
一、动画基本类型：
如下表所示，Android的动画由四种类型组成，即可在xml中定义，也可在代码中定义，如下所示：


  
  	
XML

CODE
  
渐变透明度动画效果
  	
alpha

AlphaAnimation
  
渐变尺寸伸缩动画效果
  	
scale

ScaleAnimation
  
画面转换位置移动动画效果
  	
translate

TranslateAnimation
  
画面转移旋转动画效果
  	
rotate

RotateAnimation


二、如何在XML文件中定义动画
1.alpha
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<!--  表示透明度从0.1到1.0,时长为3000ms。-->
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="3000"
/> 
</set>
2.scale
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <scale  
          android:interpolator=
                     "@android:anim/accelerate_decelerate_interpolator"
          android:fromXScale="0.0"
          android:toXScale="1.4"
          android:fromYScale="0.0"
          android:toYScale="1.4"
          android:pivotX="50%"
          android:pivotY="50%"
          android:fillAfter="false"
          android:duration="700" />
</set>
<!-- 尺寸伸缩动画效果 scale
       属性：interpolator 指定一个动画的插入器，共三种:
            accelerate_decelerate_interpolator  加速-减速 动画插入器
            accelerate_interpolator        加速-动画插入器
            decelerate_interpolator        减速- 动画插入器
        其他的属于特定的动画效果
      浮点型值：         
            fromXScale 属性为动画起始时 X坐标上的伸缩尺寸    
            toXScale   属性为动画结束时 X坐标上的伸缩尺寸 
            fromYScale 属性为动画起始时Y坐标上的伸缩尺寸    
            toYScale   属性为动画结束时Y坐标上的伸缩尺寸 
            说明:
                 以上四种属性值  
                    0.0表示收缩到没有 
                    1.0表示正常无伸缩     
                    值小于1.0表示收缩  
                    值大于1.0表示放大 
            pivotX     属性为动画相对于物件的X坐标的开始位置
            pivotY     属性为动画相对于物件的Y坐标的开始位置 
            说明:
                    以上两个属性值 从0%-100%中取值
                    50%为物件的X或Y方向坐标上的中点位置 
        长整型值：
            duration  属性为动画持续时间
            说明:   时间以毫秒为单位
        布尔型值:
            fillAfter 属性 当设置为true ，该动画转化在动画结束后被应用
-->
3.translate
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="30"
android:toXDelta="-80"
android:fromYDelta="30"
android:toYDelta="300"
android:duration="2000"
/>
<!-- translate 位置转移动画效果
        整型值:
            fromXDelta 属性为动画起始时 X坐标上的位置    
            toXDelta   属性为动画结束时 X坐标上的位置
            fromYDelta 属性为动画起始时 Y坐标上的位置
            toYDelta   属性为动画结束时 Y坐标上的位置
            注意:
                     没有指定fromXType toXType fromYType toYType 时候，
                     默认是以自己为相对参照物             
        长整型值：
            duration  属性为动画持续时间
            说明:   时间以毫秒为单位
-->
</set>
4.rotate
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate 
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromDegrees="0" 
        android:toDegrees="+350"         
        android:pivotX="50%" 
        android:pivotY="50%"     
        android:duration="3000" />  
<!-- rotate 旋转动画效果
       属性：interpolator 指定一个动画的插入器，共三种:
                accelerate_decelerate_interpolator   加速-减速 动画插入器
                accelerate_interpolator               加速-动画插入器
                decelerate_interpolator               减速- 动画插入器
             其他的属于特定的动画效果                           
       浮点数型值:
            fromDegrees 属性为动画起始时物件的角度    
            toDegrees   属性为动画结束时物件旋转的角度 可以大于360度        
            说明:
                     当角度为负数——表示逆时针旋转
                     当角度为正数——表示顺时针旋转              
                     (负数from——to正数:顺时针旋转)   
                     (负数from——to负数:逆时针旋转) 
                     (正数from——to正数:顺时针旋转) 
                     (正数from——to负数:逆时针旋转)
            pivotX     属性为动画相对于物件的X坐标的开始位置
            pivotY     属性为动画相对于物件的Y坐标的开始位置                
            说明:        以上两个属性值 从0%-100%中取值
                         50%为物件的X或Y方向坐标上的中点位置
        长整型值：
            duration  属性为动画持续时间
            说明:       时间以毫秒为单位
-->
</set>
三、如何使用XML中定义的动画
public static Animation loadAnimation (Contextcontext, int id)
//第一个参数Context为程序的上下文   
//第二个参数id为动画XML文件的引用
//例子：
myAnimation=AnimationUtils.loadAnimation(this,R.anim.my_action);
//使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件

四、如何在java代码中定义动画
1．代码：
//在代码中定义 动画实例对象
private Animation myAnimation_Alpha;
private Animation myAnimation_Scale;
private Animation myAnimation_Translate;
private Animation myAnimation_Rotate;
    
//根据各自的构造方法来初始化一个实例对象
myAnimation_Alpha=new AlphaAnimation(0.1f, 1.0f);
myAnimation_Scale =new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
             Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
myAnimation_Translate=new TranslateAnimation(30.0f, -80.0f, 30.0f, 300.0f);
myAnimation_Rotate=new RotateAnimation(0.0f, +350.0f,
               Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
2. 分析：
1.1 AlphaAnimation

第一步：AlphaAnimation类对象定义 
private AlphaAnimation myAnimation_Alpha;
第二步：AlphaAnimation类对象构造
AlphaAnimation(float fromAlpha, float toAlpha) 
//第一个参数fromAlpha为 动画开始时候透明度
//第二个参数toAlpha为 动画结束时候透明度
myAnimation_Alpha=new AlphaAnimation(0.1f, 1.0f);
//说明: 
//                0.0表示完全透明
//                1.0表示完全不透明
第三步：设置动画持续时间 
myAnimation_Alpha.setDuration(5000);
//设置时间持续时间为 5000毫秒

1.2 ScaleAnimation
第一步：ScaleAnimation类对象定义 
private AlphaAnimation myAnimation_Scale;
第二步：ScaleAnimation类对象构造
ScaleAnimation(float fromX, float toX, float fromY, float toY,
           int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)
//第一个参数fromX为动画起始时 X坐标上的伸缩尺寸    
//第二个参数toX为动画结束时 X坐标上的伸缩尺寸     
//第三个参数fromY为动画起始时Y坐标上的伸缩尺寸    
//第四个参数toY为动画结束时Y坐标上的伸缩尺寸  
/*说明:
                    以上四种属性值    
                    0.0表示收缩到没有 
                    1.0表示正常无伸缩     
                    值小于1.0表示收缩  
                    值大于1.0表示放大
*/
//第五个参数pivotXType为动画在X轴相对于物件位置类型  
//第六个参数pivotXValue为动画相对于物件的X坐标的开始位置
//第七个参数pivotXType为动画在Y轴相对于物件位置类型   
//第八个参数pivotYValue为动画相对于物件的Y坐标的开始位置
myAnimation_Scale =new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
             Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
第三步：设置动画持续时间
myAnimation_Scale.setDuration(700);
//设置时间持续时间为 700毫秒
1.3 TranslateAnimation
第一步：TranslateAnimation类对象定义 
private AlphaAnimation myAnimation_Translate;
第二步：TranslateAnimation类对象构造 
TranslateAnimation(float fromXDelta, float toXDelta,
                       float fromYDelta, float toYDelta) 

//第一个参数fromXDelta为动画起始时 X坐标上的移动位置
//第二个参数toXDelta为动画结束时 X坐标上的移动位置
//第三个参数fromYDelta为动画起始时Y坐标上的移动位置
//第四个参数toYDelta为动画结束时Y坐标上的移动位置 

第三步：设置动画持续时间 m
myAnimation_Translate.setDuration(2000);

1.4 RotateAnimation
第一步：RotateAnimation类对象定义
private AlphaAnimation myAnimation_Rotate;

第二步：RotateAnimation类对象构造
RotateAnimation(float fromDegrees, float toDegrees, 
            int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)

//第一个参数fromDegrees为动画起始时的旋转角度
//第二个参数toDegrees为动画旋转到的角度
//第三个参数pivotXType为动画在X轴相对于物件位置类型  
//第四个参数pivotXValue为动画相对于物件的X坐标的开始位置
//第五个参数pivotXType为动画在Y轴相对于物件位置类型
//第六个参数pivotYValue为动画相对于物件的Y坐标的开始位置
myAnimation_Rotate=new RotateAnimation(0.0f, +350.0f,
               Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
第三步：设置动画持续时间
myAnimation_Rotate.setDuration(3000);
五、如何使用java代码中的动画效果
使用从View父类继承过来的方法startAnimation()来为View或是子类View等等添加一个动画效果
public void startAnimation (Animation animation)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        Frame动画主要是通过AnimationDrawable类来实现的，它有start()和stop()两个重要的方法来启动和停止动画。Frame动画一般通过XML文件配置，在工程的res/anim目录下创建一个XML配置文件，该配置文件有一个<animation-list>根元素和若干个<item>子元素。
    实现一个人跳舞的Frame动画，6张图片如下所示：


1、把这6张图片放到res/drawable目录下，分别取名为：p01.png，p02.png，p03.png，p04.png，p05.png，p06.png。
2、在res/anim目录下创建一个XML配置文件，文件名为：dance.xml，文件内容：
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:apk="http://schemas.android.com/apk/res/android" apk:oneshot="false">
    <item apk:drawable="@drawable/p01" apk:duration="500" />
    <item apk:drawable="@drawable/p02" apk:duration="500" />
    <item apk:drawable="@drawable/p03" apk:duration="500" />
    <item apk:drawable="@drawable/p04" apk:duration="500" />
    <item apk:drawable="@drawable/p05" apk:duration="500" />
    <item apk:drawable="@drawable/p06" apk:duration="500" />
</animation-list>
    apk:oneshot指示是否只运行一次，设置为false则意味着循环播放。
3、在res/layout目录下创建layout配置文件dance.xml，文件内容：
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:apk="http://schemas.android.com/apk/res/android" apk:orientation="vertical" apk:layout_width="fill_parent" apk:layout_height="fill_parent">
    <!-- Frame动画图片 -->
    <ImageView apk:id="@+id/ImgDance" apk:layout_width="wrap_content" apk:layout_height="wrap_content" apk:background="@anim/dance" />
    
    <!-- 动画控制按钮 -->
    <LinearLayout apk:layout_width="fill_parent" apk:layout_height="wrap_content" apk:orientation="horizontal">
        <Button apk:text="开始" apk:layout_width="wrap_content" apk:layout_height="wrap_content" apk:onClick="onStartDance" />
        <Button apk:text="结束" apk:layout_width="wrap_content" apk:layout_height="wrap_content" apk:onClick="onStopDance" />
    </LinearLayout>
</LinearLayout>
    apk:background使用上面的动画作为背景，意味着要取得动画，只要取得该View的背景即可，当然可以在代码中通过设置背景的方式指定；
    apk:onClick指示按钮的动作，当然可以在代码中通过实现OnClickListener的方式实现。
4、Activity代码：
package com.aboy.android.study.animation;
  
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.aboy.android.study.R;
  
/**
 * Frame动画
 */
public class FrameActivity extends Activity {
    public static final String TAG = "FrameActivity";
      
    // 显示动画的组件
    private ImageView imgDance;
    // Frame动画
    private AnimationDrawable animDance;
      
    /** 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    public void onCreate(Bundle cycle) {
        super.onCreate(cycle);
        super.setContentView(R.layout.dance);
          
        // 实例化组件
        this.imgDance = (ImageView) super.findViewById(R.id.ImgDance);
          
        // 获得背景（6个图片形成的动画）
        this.animDance = (AnimationDrawable) this.imgDance.getBackground();
    }
      
    /**
     * 按钮：开始‘跳舞’动画
     */
    public void onStartDance(View view) {
        this.animDance.start();
    }
      
    /**
     * 按钮：停止‘跳舞’动画
     */
    public void onStopDance(View view) {
        this.animDance.stop();
    }
      
}
    代码就那么的几行，运行之后，点击“开始”按钮后，动画一直不停的播放，直到点击“停止”为止。