1. 程式人生 > >Android之ObjectAnimator使用記錄

Android之ObjectAnimator使用記錄

常用的方法:

注意:最後一個引數為可變引數,當只傳一個值時,系統會自動呼叫第二個引數對應的get方法來獲取初始值,若沒有對應的get方法,則會使用對應變數的預設值沒初始值。 public static ObjectAnimator ofFloat(Object target, String propertyName, float... values)

public static ObjectAnimator ofInt(Object target, String propertyName, int... values)

public static ObjectAnimator ofObject(Object target, String propertyName,TypeEvaluator evaluator, Object... values)

常用引數:
1、透明度:
     alpha    0~1之間的值

2、旋轉度數:
     rotation:  繞Z軸旋轉
     rotationX: 繞X軸旋轉
     rotationY: 繞Y軸旋轉

3、平移:
     translationX: X軸平移
     translationY: Y軸平移

4、縮放:
     scaleX: 縮放X軸
     scaleY: 縮放Y軸

自定義一個ObjectAnimator的屬性:

一:我們需要定義一個物件,如下Point,包含屬性 :半徑  radius 。

public class Point {
    private int radius;

    public Point(int radius){
        this.radius= radius;
    }

    public int getRadius() {
        return radius;
    }

    public void setRadius(int radius) {
        this.radius= radius;
    }
}

二:自定義View初始化我們的Point類,在onDraw中根據我們的Point的半徑來畫圓;然後定義一個函式 setPointRadius,該方法的 ‘pointRadius’ 就是我們ObjectAnimator 的屬性。

public class CircleView extends View {

    private Point point = new Point(100);
    private Paint paint = new Paint();
    private int centerX = 100;
    private int centerY = 100;


    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mPoint != null){
            paint.setAntiAlias(true);
            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(centerX, centerY, point.getRadius(), paint);
        }
        super.onDraw(canvas);
    }


    /**
        第一點,這個set函式所相應的屬性應該是pointRadius或者PointRadius。前面我們已經講了第一                
        個字母大寫和小寫無所謂,後面的字母必須保持與set函式全然一致。 
        第二點,在setPointRadius中,先將當前動畫傳過來的值儲存到point中。做為當前圓形的半徑。
        第三點,invalidate(),強制介面重新整理,在介面重新整理後。就開始執行onDraw()函式。
      */
    void setPointRadius(int radius){
        point.setRadius(radius);
        invalidate();
    }

}

三:初始化ObjectAnimator , 並啟動動畫。

 ObjectAnimator animator = ObjectAnimator.ofInt(view, "pointRadius", 100, 300, 100);
 animator.setDuration(2000);
 animator.start();

 四:我們通過  addListener  新增動畫狀態的監聽。

animator.addListener(new AnimatorListenerAdapter() {

//包含相關的回掉方法
             
});

以上為ObjectAnimator 動畫的基本使用方法。