使用动画绘制飘动的云朵

飘动的云朵

这里所讲飘动的云朵,其实内容很简单,就是实现使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;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章