使用动画绘制飘动的云朵

飘动的云朵

这里所讲飘动的云朵,其实内容很简单,就是实现使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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值