Android開發之屬性動畫

yungfan發表於2016-04-14

Android動畫主要分為3種

何為屬性動畫?

通過改變物件的屬性以達到動畫的效果,API 11以上可以用,如果想相容舊版本請使用 https://github.com/JakeWharton/NineOldAndroids 。屬性動畫的預設的時間為300ms,它可以在時間間隔內完成物件從一個屬性值到另外一個屬性值的改變。比較常用的屬性動畫物件有: ValueAnimatorObjectAnimatorAnimatorSet,其中ObjectAnimatorValueAnimator的子類,AnimatorSet代表動畫集合。

如何使用?

首先佈局和Activity的準備程式碼和之前一樣,即在佈局中放置一個ImageView,然後在程式中獲取,接下來介紹幾種常見動畫的使用

1、平移動畫

 /**
     * 1.5秒 將影象向Y軸正方向移動500,translationY可以換成translationX
     */
private void translateAni() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(img, "translationY", 500);

        animator.setDuration(1500);

        animator.start();
}
複製程式碼

測試執行

translate.gif

2、縮放動畫

 /**
     * 1.5秒 將影象沿Y從1.0放大到1.5,注意這裡屬性值可以為scaleX和scaleY,但設定scale是不行的
     */
private void scaleAni() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(img, "scaleY", 1, 1.5f);

        animator.setDuration(1500);

        animator.start();
}
複製程式碼

測試執行

scale.gif

3、旋轉動畫

 /**
     * 1.5秒 將影象軸旋轉360度
     */
private void rotateAni() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(img, "rotation", 0, 360);

        animator.setDuration(1500);

        animator.start();
}
複製程式碼

測試執行

rotate.gif

4、透明度動畫

 /**
     * 1.5秒 將影象的透明度從1變到0.2
     */
private void alphaAni() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(img, "alpha", 1, 0.2f);

        animator.setDuration(1500);

        animator.start();
}
複製程式碼

測試執行

alpha.gif

5、動畫集合

/**
     * 屬性集合 將上述動畫集合起來一起放一遍
     */
private void aniSet() {

        AnimatorSet set = new AnimatorSet();

        set.playTogether(
                ObjectAnimator.ofFloat(img, "translationY", 500),
                ObjectAnimator.ofFloat(img, "scaleY", 1, 1.5f),
                ObjectAnimator.ofFloat(img, "scaleX", 1, 1.5f),
                ObjectAnimator.ofFloat(img, "rotation", 0, 360),
                ObjectAnimator.ofFloat(img, "alpha", 1, 0.2f)
        );


        set.setDuration(3000);

        set.start();
}
複製程式碼

測試執行

set.gif

6、顏色漸變動畫

這種方式比較坑,試了很多種,按上面那些方式行不通,最後想到這個應該是屬於任意屬性的範疇,所以採用了ValueAnimator,監聽動畫過程,自己來實現屬性的改變,果然成功了:

 // 顏色漸變動畫 這個要注意 無法直接採用上面的方法直接來設定 設定了也是無效的 這裡涉及到給任意屬性設定動畫的問題
private void colorAni(int startColor, int endColor) {

        ValueAnimator valueAnimator = ValueAnimator.ofArgb(startColor, endColor);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {

                //找到Activity的預設View
                View view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);

                //改變背景色
                view.setBackgroundColor((Integer) valueAnimator.getAnimatedValue());

            }
        });

        valueAnimator.setDuration(3000);
        valueAnimator.start();
}
複製程式碼

測試執行

backgroundColor.gif

程式碼地址

相關文章