Android 屬性動畫(Property Animation)

1、概述

Android提供了幾種動畫類型:View Animation 、Drawable Animation 、Property Animation 。View Animation相當簡單,不過只能支持簡單的縮放、平移、旋轉、透明度基本的動畫,且有一定的侷限性。比如:你希望View有一個顏色的切換動畫;你希望可以使用3D旋轉動畫;你希望當動畫停止時,View的位置就是當前的位置;這些View Animation都無法做到。這就是Property Animation產生的原因,本篇博客詳細介紹Property Animation的用法。至於Drawable Animation,嗯,略~

2、相關API

Property Animation故名思議就是通過動畫的方式改變對象的屬性了,我們首先需要了解幾個屬性:

Duration動畫的持續時間,默認300ms。

Time interpolation:時間差值,乍一看不知道是什麼,但是我說LinearInterpolator、AccelerateDecelerateInterpolator,大家一定知道是幹嘛的了,定義動畫的變化率。

Repeat count and behavior:重複次數、以及重複模式;可以定義重複多少次;重複時從頭開始,還是反向。

Animator sets: 動畫集合,你可以定義一組動畫,一起執行或者順序執行。

Frame refresh delay:幀刷新延遲,對於你的動畫,多久刷新一次幀;默認爲10ms,但最終依賴系統的當前狀態;基本不用管。

相關的類

ObjectAnimator  動畫的執行類,後面詳細介紹

ValueAnimator 動畫的執行類,後面詳細介紹 

AnimatorSet 用於控制一組動畫的執行:線性,一起,每個動畫的先後執行等。

AnimatorInflater 用戶加載屬性動畫的xml文件

TypeEvaluator  類型估值,主要用於設置動畫操作屬性的值。

TimeInterpolator 時間插值,上面已經介紹。

總的來說,屬性動畫就是,動畫的執行類來設置動畫操作的對象的屬性、持續時間,開始和結束的屬性值,時間差值等,然後系統會根據設置的參數動態的變化對象的屬性。

3、ObjectAnimator實現動畫

之所以選擇ObjectAnimator爲第一個~~是因爲,這個實現最簡單~~一行代碼,秒秒鐘實現動畫,下面看個例子:
佈局文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/id_container" >
    <ImageView
        android:id="@+id/id_ball"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/mv" 
        android:scaleType="centerCrop"
        android:onClick="rotateyAnimRun"
        />
</RelativeLayout>

很簡單,就一張妹子圖片~
Activity代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.zhy_property_animation;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class ObjectAnimActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_for_anim);
}
public void rotateyAnimRun(View view)
{
 ObjectAnimator//
 .ofFloat(view, "rotationX"0.0F, 360.0F)//
 .setDuration(500)//
 .start();
}
}

效果:

是不是一行代碼就能實現簡單的動畫~~

對於ObjectAnimator

1、提供了ofInt、ofFloat、ofObject,這幾個方法都是設置動畫作用的元素、作用的屬性、動畫開始、結束、以及中間的任意個屬性值。

當對於屬性值,只設置一個的時候,會認爲當前對象該屬性的值爲開始(getPropName反射獲取),然後設置的值爲終點。如果設置兩個,則一個爲開始、一個爲結束~~~

動畫更新的過程中,會不斷調用setPropName更新元素的屬性,所有使用ObjectAnimator更新某個屬性,必須得有getter(設置一個屬性值的時候)和setter方法~

2、如果你操作對象的該屬性方法裏面,比如上例的setRotationX如果內部沒有調用view的重繪,則你需要自己按照下面方式手動調用。

?
1
2
3
4
5
6
7
8
9
anim.addUpdateListener(new AnimatorUpdateListener()
{
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
//view.postInvalidate();
//view.invalidate();
}
});

3、看了上面的例子,因爲設置的操作的屬性只有一個,那麼如果我希望一個動畫能夠讓View既可以縮小、又能夠淡出(3個屬性scaleX,scaleY,alpha),只使用ObjectAnimator咋弄?

想法是不是很不錯,可能會說使用AnimatorSet啊,這一看就是一堆動畫塞一起執行,但是我偏偏要用一個ObjectAnimator實例實現呢~下面看代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void rotateyAnimRun(final View view)
{
ObjectAnimator anim = ObjectAnimator//
.ofFloat(view, "zhy"1.0F,  0.0F)//
.setDuration(500);//
anim.start();
anim.addUpdateListener(new AnimatorUpdateListener()
{
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
float cVal = (Float) animation.getAnimatedValue();
view.setAlpha(cVal);
view.setScaleX(cVal);
view.setScaleY(cVal);
}
});
}

把設置屬性的那個字符串,隨便寫一個該對象沒有的屬性,就是不管~~咱們只需要它按照時間插值和持續時間計算的那個值,我們自己手動調用~

效果:

這個例子就是想說明一下,有時候換個思路不要被API所約束,利用部分API提供的功能也能實現好玩的效果~~~

比如:你想實現拋物線的效果,水平方向100px/s,垂直方向加速度200px/s*s ,咋實現呢~~可以自己用ObjectAnimator試試~

4、其實還有更簡單的方式,實現一個動畫更改多個效果:使用propertyValuesHolder

?
1
2
3
4
5
6
7
8
9
10
public void propertyValuesHolder(View view)
{
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f,
0f, 1f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f,
0, 1f);
PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f,
0, 1f);
ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY,pvhZ).setDuration(1000).start();
}
 4、ValueAnimator實現動畫

和ObjectAnimator用法很類似,簡單看一下用view垂直移動的動畫代碼:

?
1
2
3
4
5
6
public void verticalRun(View view)
{
    ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight - mBlueBall.getHeight());
    animator.setTarget(mBlueBall);
    animator.setDuration(1000).start();
}

給你的感覺是不是,坑爹啊,這和ValueAnimator有毛線區別~但是仔細看,你看會發現,沒有設置操作的屬性~~也就是說,上述代碼是沒有任何效果的,沒有指定屬性~

這就是和ValueAnimator的區別之處:ValueAnimator並沒有在屬性上做操作,你可能會問這樣有啥好處?我豈不是還得手動設置?

好處:不需要操作的對象的屬性一定要有getter和setter方法,你可以自己根據當前動畫的計算值,來操作任何屬性,記得上例的那個【我希望一個動畫能夠讓View既可以縮小、又能夠淡出(3個屬性scaleX,scaleY,alpha)】嗎?其實就是這麼個用法~

實例:

佈局文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:id="@+id/id_container"
   
    >
    <ImageView
        android:id="@+id/id_ball"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bol_blue" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="verticalRun"
            android:text="垂直" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="paowuxian"
            android:text="拋物線" />
    </LinearLayout>
</RelativeLayout>

左上角一個小球,底部兩個按鈕~我們先看一個自由落體的代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 自由落體
 * @param view
 */
public void verticalRun( View view)
{
ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight - mBlueBall.getHeight());
    animator.setTarget(mBlueBall);
    animator.setDuration(1000).start();
    //animator.setInterpolator(value)
    animator.addUpdateListener(new AnimatorUpdateListener()
{
    @Override
    public void onAnimationUpdate(ValueAnimator animation)  {
            mBlueBall.setTranslationY((Float) animation.getAnimatedValue());
        }
    });
}

與ObjectAnimator不同的就是我們自己設置元素屬性的更新~雖然多了幾行代碼,但是貌似提高靈活性~

下面再來一個例子,如果我希望小球拋物線運動【實現拋物線的效果,水平方向100px/s,垂直方向加速度200px/s*s 】,分析一下,貌似只和時間有關係,但是根據時間的變化,橫向和縱向的移動速率是不同的,我們該咋實現呢?此時就要重寫TypeValue的時候了,因爲我們在時間變化的同時,需要返回給對象兩個值,x當前位置,y當前位置:

代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * 拋物線
 * @param view
 */
public void paowuxian(View view)
{
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.setDuration(3000);
valueAnimator.setObjectValues(new PointF(00));
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.setEvaluator(new TypeEvaluator<PointF>()
{
// fraction = t / duration
@Override
public PointF evaluate(float fraction, PointF startValue,
PointF endValue)
{
Log.e(TAG, fraction * 3 "");
// x方向200px/s ,則y方向0.5 * 10 * t
PointF point = new PointF();
point.x = 200 * fraction * 3;
point.y = 0.5f * 200 * (fraction * 3) * (fraction * 3);
return point;
}
});
valueAnimator.start();
valueAnimator.addUpdateListener(new AnimatorUpdateListener()
{
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
PointF point = (PointF) animation.getAnimatedValue();
mBlueBall.setX(point.x);
mBlueBall.setY(point.y);
}
});
}

可以看到,因爲ofInt,ofFloat等無法使用,我們自定義了一個TypeValue,每次根據當前時間返回一個PointF對象,(PointF和Point的區別就是x,y的單位一個是float,一個是int;RectF,Rect也是)PointF中包含了x,y的當前位置~然後我們在監聽器中獲取,動態設置屬性:

效果圖:


有木有兩個鐵球同時落地的感覺~~對,我應該搞兩個球~~ps:物理公式要是錯了,就當沒看見哈

自定義TypeEvaluator傳入的泛型可以根據自己的需求,自己設計個Bean。

好了,我們已經分別講解了ValueAnimator和ObjectAnimator實現動畫;二者區別;如何利用部分API,自己更新屬性實現效果;自定義TypeEvaluator實現我們的需求;但是我們並沒有講如何設計插值,其實我覺得把,這個插值默認的那一串實現類夠用了~~很少,會自己去設計個超級變態的~嗯~所以:略。

5、監聽動畫的事件

對於動畫,一般都是一些輔助效果,比如我要刪除個元素,我可能希望是個淡出的效果,但是最終還是要刪掉,並不是你透明度沒有了,還佔着位置,所以我們需要知道動畫如何結束。

所以我們可以添加一個動畫的監聽:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void fadeOut(View view)
{
ObjectAnimator anim = ObjectAnimator.ofFloat(mBlueBall, "alpha"0.5f);
anim.addListener(new AnimatorListener()
{
@Override
public void onAnimationStart(Animator animation)
{
Log.e(TAG, "onAnimationStart");
}
@Override
public void onAnimationRepeat(Animator animation)
{
// TODO Auto-generated method stub
Log.e(TAG, "onAnimationRepeat");
}
@Override
public void onAnimationEnd(Animator animation)
{
Log.e(TAG, "onAnimationEnd");
ViewGroup parent = (ViewGroup) mBlueBall.getParent();
if (parent != null)
parent.removeView(mBlueBall);
}
@Override
public void onAnimationCancel(Animator animation)
{
// TODO Auto-generated method stub
Log.e(TAG, "onAnimationCancel");
}
});
anim.start();
}

這樣就可以監聽動畫的開始、結束、被取消、重複等事件~但是有時候會覺得,我只要知道結束就行了,這麼長的代碼我不能接收,那你可以使用AnimatorListenerAdapter

?
1
2
3
4
5
6
7
8
9
10
11
anim.addListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
Log.e(TAG, "onAnimationEnd");
ViewGroup parent = (ViewGroup) mBlueBall.getParent();
if (parent != null)
parent.removeView(mBlueBall);
}
});

AnimatorListenerAdapter繼承了AnimatorListener接口,然後空實現了所有的方法~

效果圖:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.example.zhy_property_animation;
import android.animation.LayoutTransition;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridLayout;
public class LayoutAnimaActivity extends Activity implements
OnCheckedChangeListener
{
private ViewGroup viewGroup;
private GridLayout mGridLayout;
private int mVal;
private LayoutTransition mTransition;
private CheckBox mAppear, mChangeAppear, mDisAppear, mChangeDisAppear;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_animator);
viewGroup = (ViewGroup) findViewById(R.id.id_container);
mAppear = (CheckBox) findViewById(R.id.id_appear);
mChangeAppear = (CheckBox) findViewById(R.id.id_change_appear);
mDisAppear = (CheckBox) findViewById(R.id.id_disappear);
mChangeDisAppear = (CheckBox) findViewById(R.id.id_change_disappear);
mAppear.setOnCheckedChangeListener(this);
mChangeAppear.setOnCheckedChangeListener(this);
mDisAppear.setOnCheckedChangeListener(this);
mChangeDisAppear.setOnCheckedChangeListener(this);
// 創建一個GridLayout
mGridLayout = new GridLayout(this);
// 設置每列5個按鈕
mGridLayout.setColumnCount(5);
// 添加到佈局中
viewGroup.addView(mGridLayout);
//默認動畫全部開啓
mTransition = new LayoutTransition();
mGridLayout.setLayoutTransition(mTransition);
}
/**
 * 添加按鈕
 
 * @param view
 */
public void addBtn(View view)
{
final Button button = new Button(this);
button.setText((++mVal) + "");
mGridLayout.addView(button, Math.min(1, mGridLayout.getChildCount()));
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mGridLayout.removeView(button);
}
});
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mTransition = new LayoutTransition();
mTransition.setAnimator(
LayoutTransition.APPEARING,
(mAppear.isChecked() ? mTransition
.getAnimator(LayoutTransition.APPEARING) : null));
mTransition
.setAnimator(
LayoutTransition.CHANGE_APPEARING,
(mChangeAppear.isChecked() ? mTransition
.getAnimator(LayoutTransition.CHANGE_APPEARING)
null));
mTransition.setAnimator(
LayoutTransition.DISAPPEARING,
(mDisAppear.isChecked() ? mTransition
.getAnimator(LayoutTransition.DISAPPEARING) : null));
mTransition.setAnimator(
LayoutTransition.CHANGE_DISAPPEARING,
(mChangeDisAppear.isChecked() ? mTransition
.getAnimator(LayoutTransition.CHANGE_DISAPPEARING)
null));
mGridLayout.setLayoutTransition(mTransition);
}
}

效果圖:


動畫有點長,耐心點看,一定要注意,是對當前View還是其他Views設置的動畫。

當然了動畫支持自定義,還支持設置時間,比如我們修改下,添加的動畫爲:

?
1
2
3
mTransition.setAnimator(LayoutTransition.APPEARING, (mAppear
.isChecked() ? ObjectAnimator.ofFloat(this"scaleX"01)
null));

則效果爲:


原本的淡入,變成了寬度從中間放大的效果~~是不是還不錯~~

9、View的anim方法

在SDK11的時候,給View添加了animate方法,更加方便的實現動畫效果。

佈局文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    >
    <ImageView
        android:id="@+id/id_ball"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bol_blue" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="viewAnim"
            android:text="View Anim" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="propertyValuesHolder"
            android:text="PropertyValuesHolder " />
         
    </LinearLayout>
</RelativeLayout>

代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.example.zhy_property_animation;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class ViewAnimateActivity extends Activity
{
protected static final String TAG = "ViewAnimateActivity";
private ImageView mBlueBall;
private float mScreenHeight;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_animator);
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
mScreenHeight = outMetrics.heightPixels;
mBlueBall = (ImageView) findViewById(R.id.id_ball);
}
public void viewAnim(View view)
{
// need API12
mBlueBall.animate()//
.alpha(0)//
.y(mScreenHeight / 2).setDuration(1000)
// need API 12
.withStartAction(new Runnable()
{
@Override
public void run()
{
Log.e(TAG, "START");
}
// need API 16
}).withEndAction(new Runnable()
{
@Override
public void run()
{
Log.e(TAG, "END");
runOnUiThread(new Runnable()
{
@Override
public void run()
{
mBlueBall.setY(0);
mBlueBall.setAlpha(1.0f);
}
});
}
}).start();
}                                                                                                                                                  }

簡單的使用mBlueBall.animate().alpha(0).y(mScreenHeight / 2).setDuration(1000).start()就能實現動畫~~不過需要SDK11,此後在SDK12,SDK16又分別添加了withStartAction和withEndAction用於在動畫前,和動畫後執行一些操作。當然也可以.setListener(listener)等操作。

使用ObjectAnimator實現上面的變化,我們可以使用:PropertyValueHolder

?
1
2
3
4
5
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f,
0f, 1f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y"0,
mScreenHeight / 20);
ObjectAnimator.ofPropertyValuesHolder(mBlueBall, pvhX, pvhY).setDuration(1000).start();

效果與上面一樣。

運行結果:




好了,關於屬性動畫基本所有的用法到此結束~~~~


發佈了22 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章