使用動畫繪製飄動的雲朵

飄動的雲朵

這裏所講飄動的雲朵,其實內容很簡單,就是實現使ImageView由左至右水平運動的動畫效果。

佈局代碼

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/sunny_bg">

    <ImageView
        android:id="@+id/iv_cloud"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/rain1_yun1"
        android:visibility="invisible"/>

</LinearLayout>

設置動畫的代碼

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //在onWindowFocusChanged()裏獲取圖片的寬度,如果在onCreate()中獲取的話,getWidth()可能會返回0
        if (hasFocus){
            DisplayMetrics dm=new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenW=dm.widthPixels;//獲取屏幕寬度

            int bitmapW=iv_cloud.getWidth();//獲取圖片寬度
            int bitmapH=iv_cloud.getHeight();//獲取圖片高度
            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            //marginLeft設置爲-bitmapW,是爲了在動畫開始後讓圖片從屏幕最左端緩緩進入
            layoutParams.setMargins(-bitmapW,bitmapH,-screenW,0);
            iv_cloud.setLayoutParams(layoutParams);//設置圖片的各種margin
            iv_cloud.setVisibility(View.VISIBLE);

            //動畫開始時,圖片從左往右進入屏幕,直至圖片完全移出屏幕後動畫結束
            ObjectAnimator animator=ObjectAnimator.ofFloat(iv_cloud,"translationX",0,screenW+bitmapW);
            animator.setDuration(20000);
            animator.setInterpolator(new MyInterpolator());//使用自定義的插值器,因爲默認插值器會使動畫的變化速度先快後慢,但這裏希望動畫勻速變化
            animator.start();
            animator.setRepeatCount(ValueAnimator.INFINITE);//使動畫循環播放
        }

    }

    //編寫自定義Interpolator,目的是使圖片勻速運動
    class MyInterpolator implements TimeInterpolator{
        @Override
        public float getInterpolation(float input) {
            return input;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章