animation动画小结(2)

来源:互联网 发布:淘宝自动回复怎么修改 编辑:程序博客网 时间:2024/05/21 10:58

声明下,这是转载大神任玉刚的文章:http://blog.csdn.net/singwhatiwanna/article/details/17639987 然后自己阅读的时候稍微加上了一些注释。

文章实现的是下面这样的一个动画:

动画分类

View动画:也叫渐变动画,针对View的动画,主要支持平移、旋转、缩放、透明度(alpha,scale,translate,rotate

Drawable动画:也叫帧动画,主要是设置View的背景,可以以动画的形式为View设置多张背景,这种情况就跟放电影似的。

对象属性动画(Android3.0新加入):可以对对象的属性进行动画而不仅仅是View,动画默认时间间隔300ms,默认帧率10ms/帧。其可以达到的效果是:在一个时间间隔内完成对象从一个属性值到另一个属性值的改变,因此,属性动画几乎是无所不能的,只要对象有这个属性,它都能实现动画效果,但是属性动画从Android3.0才有,这就严重制约了属性动画的使用,这就是开源动画库nineoldandroids的作用,采用nineoldandroids,可以在3.0以前的系统上使用属性动画,nineoldandroids的网址是:http://nineoldandroids.com。说到属性动画,就不得不提到插值器(TimeInterpolator)和估值算法(TypeEvaluator),下面介绍。

TimeInterpolator和TypeEvaluator

TimeInterpolator中文翻译为时间插值器,它的作用是根据时间流逝的百分比来计算出当前属性值改变的百分比,系统预置的有LinearInterpolator(线性插值器:匀速动画)、AccelerateDecelerateInterpolator(加速减速插值器:动画两头慢中间快)和DecelerateInterpolator(减速插值器:动画越来越慢)等;TypeEvaluator的中文翻译为类型估值算法,它的作用是根据当前属性改变的百分比来计算改变后的属性值,系统预置的有IntEvaluator(针对整型属性)、FloatEvaluator(针对浮点型属性)和ArgbEvaluator(针对Color属性)。可能这么说还有点晦涩,没关系,下面给出一个实例就很好理解了。


看上述动画,很显然上述动画是一个匀速动画,其采用了线性插值器和整型估值算法,在40ms内,View的x属性实现从0到40的变换,由于动画的默认刷新率为10ms/帧,所以该动画将分5帧进行,我们来考虑第三帧(x=20 t=20ms),当时间t=20ms的时候,时间流逝的百分比是0.5 (20/40=0.5),意味这现在时间过了一半,那x应该改变多少呢,这个就由插值器和估值算法来确定。拿线性插值器来说,当时间流逝一半的时候,x的变换也应该是一半,即x的改变是0.5,为什么呢?因为它是线性插值器,是实现匀速动画的,下面看它的源码:

public class LinearInterpolator implements Interpolator {    public LinearInterpolator() {    }        public LinearInterpolator(Context context, AttributeSet attrs) {    }        public float getInterpolation(float input) {        return input;    }}

很显然,线性插值器的返回值和输入值一样,因此插值器返回的值是0.5,这意味着x的改变是0.5,这个时候插值器的工作就完成了。

具体x变成了什么值,这个需要估值算法来确定,我们来看看整型估值算法的源码:

public class IntEvaluator implements TypeEvaluator<Integer> {    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {        int startInt = startValue;        return (int)(startInt + fraction * (endValue - startInt));    }}

上述算法很简单,evaluate的三个参数分别表示:估值小数、开始值和结束值,对应于我们的例子就分别是:0.5,0,40。根据上述算法,整型估值返回给我们的结果是20,这就是(x=20 t=20ms)的由来。

说明:属性动画要求该属性有set方法和get方法(可选);插值器和估值算法除了系统提供的外,我们还可以自定义,实现方式也很简单,因为插值器和估值算法都是一个接口,且内部都只有一个方法,我们只要派生一个类实现接口就可以了,然后你就可以做出千奇百怪的动画效果。具体一点就是:自定义插值器需要实现Interpolator或者TimeInterpolator,自定义估值算法需要实现TypeEvaluator。还有就是如果你对其他类型(非int、float、color)做动画,你必须要自定义类型估值算法。

nineoldandroids介绍

其功能和android.animation.*中的类的功能完全一致,使用方法完全一样,只要我们用nineoldandroids来编写动画,就可以在所有的Android系统上运行。比较常用的几个动画类是:ValueAnimator、ObjectAnimator和AnimatorSet,其中ObjectAnimator继承自ValueAnimator,AnimatorSet是动画集,可以定义一组动画。使用起来也是及其简单的,下面举几个小栗子。

栗子1:改变一个对象(myObject)的 translationY属性,让其沿着Y轴向上平移一段距离:它的高度,该动画在默认时间内完成,动画的完成时间是可以定义的,想要更灵活的效果我们还可以定义插值器和估值算法,但是一般来说我们不需要自定义,系统已经预置了一些,能够满足常用的动画。

ObjectAnimator.ofFloat(myObject, "translationY", -myObject.getHeight()).start();


栗子2:改变一个对象的背景色属性,典型的情形是改变View的背景色,下面的动画可以让背景色在3秒内实现从0xFFFF8080到0xFF8080FF的渐变,并且动画会无限循环而且会有反转的效果

ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor", /*Red*/0xFFFF8080, /*Blue*/0xFF8080FF);colorAnim.setDuration(3000);colorAnim.setEvaluator(new ArgbEvaluator());colorAnim.setRepeatCount(ValueAnimator.INFINITE);colorAnim.setRepeatMode(ValueAnimator.REVERSE);colorAnim.start();

栗子3:动画集合,5秒内对View的旋转、平移、缩放和透明度都进行了改变

AnimatorSet set = new AnimatorSet();set.playTogether(    ObjectAnimator.ofFloat(myView, "rotationX", 0, 360),    ObjectAnimator.ofFloat(myView, "rotationY", 0, 180),    ObjectAnimator.ofFloat(myView, "rotation", 0, -90),    ObjectAnimator.ofFloat(myView, "translationX", 0, 90),    ObjectAnimator.ofFloat(myView, "translationY", 0, 90),    ObjectAnimator.ofFloat(myView, "scaleX", 1, 1.5f),    ObjectAnimator.ofFloat(myView, "scaleY", 1, 0.5f),    ObjectAnimator.ofFloat(myView, "alpha", 1, 0.25f, 1));set.setDuration(5 * 1000).start();

栗子4:下面是个简单的调用方式,其animate方法是nineoldandroids特有的

Button myButton = (Button)findViewById(R.id.myButton);//Note: in order to use the ViewPropertyAnimator like this add the following import://  import static com.nineoldandroids.view.ViewPropertyAnimator.animate;animate(myButton).setDuration(2000).rotationYBy(720).x(100).y(100);

栗子5:一个采用nineoldandroids实现的稍微复杂点的动画

布局xml如下:

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <Button        android:id="@+id/menu"        style="@style/MenuStyle"        android:background="@drawable/menu" />    <Button        android:id="@+id/item1"        style="@style/MenuItemStyle"        android:background="@drawable/circle1"        android:visibility="gone" />    <Button        android:id="@+id/item2"        style="@style/MenuItemStyle"        android:background="@drawable/circle2"        android:visibility="gone" />    <Button        android:id="@+id/item3"        style="@style/MenuItemStyle"        android:background="@drawable/circle3"        android:visibility="gone" />    <Button        android:id="@+id/item4"        style="@style/MenuItemStyle"        android:background="@drawable/circle4"        android:visibility="gone" />    <Button        android:id="@+id/item5"        style="@style/MenuItemStyle"        android:background="@drawable/circle5"        android:visibility="gone" /></FrameLayout>


代码如下:

public class MainActivity extends Activity implements OnClickListener {    private static final String TAG = "MainActivity";    private Button mMenuButton;    private Button mItemButton1;    private Button mItemButton2;    private Button mItemButton3;    private Button mItemButton4;    private Button mItemButton5;    private boolean mIsMenuOpen = false;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();    }    @TargetApi(Build.VERSION_CODES.HONEYCOMB)    private void initView() {        mMenuButton = (Button) findViewById(R.id.menu);        mMenuButton.setOnClickListener(this);        mItemButton1 = (Button) findViewById(R.id.item1);        mItemButton1.setOnClickListener(this);        mItemButton2 = (Button) findViewById(R.id.item2);        mItemButton2.setOnClickListener(this);        mItemButton3 = (Button) findViewById(R.id.item3);        mItemButton3.setOnClickListener(this);        mItemButton4 = (Button) findViewById(R.id.item4);        mItemButton4.setOnClickListener(this);        mItemButton5 = (Button) findViewById(R.id.item5);        mItemButton5.setOnClickListener(this);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        mMenuButton.performClick();        getMenuInflater().inflate(R.menu.main, menu);        return false;    }    @Override    public void onClick(View v) {        if (v == mMenuButton) {            if (!mIsMenuOpen) {                mIsMenuOpen = true;                doAnimateOpen(mItemButton1, 0, 5, 300);                doAnimateOpen(mItemButton2, 1, 5, 300);                doAnimateOpen(mItemButton3, 2, 5, 300);                doAnimateOpen(mItemButton4, 3, 5, 300);                doAnimateOpen(mItemButton5, 4, 5, 300);            } else {                mIsMenuOpen = false;                doAnimateClose(mItemButton1, 0, 5, 300);                doAnimateClose(mItemButton2, 1, 5, 300);                doAnimateClose(mItemButton3, 2, 5, 300);                doAnimateClose(mItemButton4, 3, 5, 300);                doAnimateClose(mItemButton5, 4, 5, 300);            }        } else {            Toast.makeText(this, "你点击了" + v, Toast.LENGTH_SHORT).show();        }    }    /**     * 打开菜单的动画     * @param view 执行动画的view     * @param index view在动画序列中的顺序     * @param total 动画序列的个数     * @param radius 动画半径     */    private void doAnimateOpen(View view, int index, int total, int radius) {        if (view.getVisibility() != View.VISIBLE) {            view.setVisibility(View.VISIBLE);        }        double degree = Math.PI * index / ((total - 1) * 2);        int translationX = (int) (radius * Math.cos(degree));        int translationY = (int) (radius * Math.sin(degree));        Log.d(TAG, String.format("degree=%f, translationX=%d, translationY=%d",                degree, translationX, translationY));        AnimatorSet set = new AnimatorSet();        //包含平移、缩放和透明度动画        set.playTogether(                ObjectAnimator.ofFloat(view, "translationX", 0, translationX),                ObjectAnimator.ofFloat(view, "translationY", 0, translationY),                ObjectAnimator.ofFloat(view, "scaleX", 0f, 1f),                ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f),                ObjectAnimator.ofFloat(view, "alpha", 0f, 1));        //动画周期为500ms        set.setDuration(1 * 500).start();    }    /**     * 关闭菜单的动画     * @param view 执行动画的view     * @param index view在动画序列中的顺序     * @param total 动画序列的个数     * @param radius 动画半径     */    private void doAnimateClose(final View view, int index, int total,            int radius) {        if (view.getVisibility() != View.VISIBLE) {            view.setVisibility(View.VISIBLE);        }        double degree = Math.PI * index / ((total - 1) * 2);        int translationX = (int) (radius * Math.cos(degree));        int translationY = (int) (radius * Math.sin(degree));        Log.d(TAG, String.format("degree=%f, translationX=%d, translationY=%d",                degree, translationX, translationY));        AnimatorSet set = new AnimatorSet();      //包含平移、缩放和透明度动画        set.playTogether(                ObjectAnimator.ofFloat(view, "translationX", translationX, 0),                ObjectAnimator.ofFloat(view, "translationY", translationY, 0),                ObjectAnimator.ofFloat(view, "scaleX", 1f, 0f),                ObjectAnimator.ofFloat(view, "scaleY", 1f, 0f),                ObjectAnimator.ofFloat(view, "alpha", 1f, 0f));        //为动画加上事件监听,当动画结束的时候,我们把当前view隐藏        set.addListener(new AnimatorListener() {            @Override            public void onAnimationStart(Animator animator) {            }            @Override            public void onAnimationRepeat(Animator animator) {            }            @Override            public void onAnimationEnd(Animator animator) {                view.setVisibility(View.GONE);            }            @Override            public void onAnimationCancel(Animator animator) {            }        });        set.setDuration(1 * 500).start();    }}


在自己重写上面的demo的时候发现:在导入nineoldandroids 包的时候,假如android自带的android.animation包也被导入,那么就有可能产生某些方法比如playTogether会报错,nineoldandroids的作用就是让animator可以在低于3.0版本上也可以使用。

上面有讲到过自定义插值器实现interpolater,常见的插值器如下:

Interpolator对象资源ID功能作用AccelerateDecelerateInterpolator@android:anim/accelerate_decelerate_interpolator先加速再减速AccelerateInterpolator@android:anim/accelerate_interpolator加速AnticipateInterpolator@android:anim/anticipate_interpolator先回退一小步然后加速前进AnticipateOvershootInterpolator@android:anim/anticipate_overshoot_interpolator在上一个基础上超出终点一小步再回到终点BounceInterpolator@android:anim/bounce_interpolator最后阶段弹球效果CycleInterpolator@android:anim/cycle_interpolator周期运动DecelerateInterpolator@android:anim/decelerate_interpolator减速LinearInterpolator@android:anim/linear_interpolator匀速OvershootInterpolator@android:anim/overshoot_interpolator快速到达终点并超出一小步最后回到终点

然后我们可以这样使用一个插值器:

<set android:interpolator="@android:anim/accelerate_interpolator">...</set>

如果只简单地引用这些插值器还不能满足需要的话,我们要考虑一下个性化插值器。我们可以创建一个插值器资源修改插值器的属性,比如修改AnticipateInterpolator的加速速率,调整CycleInterpolator的循环次数等。为了完成这种需求,我们需要创建XML资源文件,然后将其放于/res/anim下,然后再动画元素中引用即可。我们先来看一下几种常见的插值器可调整的属性:

<accelerateDecelerateInterpolator> 无

<accelerateInterpolator> android:factor 浮点值,加速速率,默认为1

<anticipateInterploator> android:tension 浮点值,起始点后退的张力、拉力数,默认为2

<anticipateOvershootInterpolator> android:tension 同上 android:extraTension 浮点值,拉力的倍数,默认为1.5(2  * 1.5)

<bounceInterpolator> 无

<cycleInterplolator> android:cycles 整数值,循环的个数,默认为1

<decelerateInterpolator> android:factor 浮点值,减速的速率,默认为1

<linearInterpolator> 无

<overshootInterpolator> 浮点值,超出终点后的张力、拉力,默认为2

下面我们就拿最后一个插值器来举例:

<?xml version="1.0" encoding="utf-8"?><overshootInterpolator xmlns:android="http://schemas.android.com/apk/res/android"    android:tension="7.0"/>


上面的代码中,我们把张力改为7.0,然后将此文件命名为my_overshoot_interpolator.xml,放置于/res/anim下,我们就可以引用到自定义的插值器了:

<scale xmlns:android="http://schemas.android.com/apk/res/android"    android:interpolator="@anim/my_overshoot_interpolator"    .../>

如果以上这些简单的定义还不能满足我们的需求,那么我们就需要考虑一下自己定义插值器类了。

我们可以实现Interpolator接口,因为上面所有的Interpolator都实现了Interpolator接口,这个接口定义了一个方法:float getInterpolation(float input);

此方法由系统调用,input代表动画的时间,在0和1之间,也就是开始和结束之间。

线性(匀速)插值器定义如下:

    public float getInterpolation(float input) {        return input;    }


加速减速插值器定义如下:

    public float getInterpolation(float input) {        return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;    }

只要实现Interpolator接口,getInterpolation方法里面怎么写就随你自己咯。










0 0
原创粉丝点击