栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android案例(逐帧动画和属性动画)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android案例(逐帧动画和属性动画)

1、实现效果

2、布局




    

    



butterfly_animation.xml



    
    
    
    
    
    
    
    


bird_animation.xml



    
    
    
    
    
    
    
    


3、java代码

package com.example.butterflyapplication;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private int screenWidth;
    private ImageView iv_butterfly,iv_bird;
    private AnimationDrawable animation;
    private AnimatorSet flyAnimatorSet;
    private ObjectAnimator objectAnimator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    private void init(){
        getWindowWidth();
        iv_butterfly=findViewById(R.id.iv_butterfly);
        iv_bird=findViewById(R.id.iv_bird);
        flyAnimation(1); //实现蝴蝶飞舞的效果
        flyAnimation(2); //实现小鸟飞舞的效果
    }
    
    private void getWindowWidth(){
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth= dm.widthPixels;
    }
    
    private void flyAnimation(int flag){
        flyAnimatorSet=new AnimatorSet();
        if (flag==1) {
            //获取逐帧动画
            animation= (AnimationDrawable) iv_butterfly.getBackground();
            //设置蝴蝶在水平方向移动的距离为屏幕的宽度-270
            objectAnimator = ObjectAnimator.ofFloat(iv_butterfly,
                    "translationX", screenWidth - 270);
            objectAnimator.setDuration(3*1000);//设置动画时间为3秒
        }else if (flag==2){
            //获取逐帧动画
            animation= (AnimationDrawable) iv_bird.getBackground();
            //设置小鸟在水平方向移动的距离为屏幕的宽度
            objectAnimator = ObjectAnimator.ofFloat(iv_bird,
                    "translationX", screenWidth);
            objectAnimator.setRepeatCount(Animation.RESTART); //重新开始播放动画
            objectAnimator.setRepeatCount(Animation.INFINITE);//循环播放动画
            objectAnimator.setDuration(10*1000);//设置动画时间为10秒
        }
        objectAnimator.setInterpolator(new LinearInterpolator());//设置线性插值器
        flyAnimatorSet.play(objectAnimator);
        animation.start();     //开启逐帧动画
        flyAnimatorSet.start();//开启属性动画
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003266.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号