蝴蝶飞舞- (补间动画+逐帧动画)

AnimationDrawable animationDrawable; //逐帧动画
    //移动蝴蝶位置的定时器
    Timer tmrTranslate;
    TimerTask timerTask;

    ImageView iv; //存放蝴蝶的控件

    //蝴蝶当前位置
    float ivCurX;
    float ivCurY;

    //蝴蝶可飞的最大范围
    int maxWidth;
    int maxHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        //获得屏幕大小
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);
        maxWidth = displayMetrics.heightPixels;
        maxHeight = displayMetrics.widthPixels;

        //播放动画的控件
        iv = (ImageView)findViewById(R.id.iv_test);
        //初始化
        ivCurX = iv.getX();
        ivCurY = iv.getY();
        tmrTranslate = new Timer();
        //得到逐帧动画
        animationDrawable = (AnimationDrawable)iv.getDrawable();

    }

    //处理界面控件移动
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            if(msg.what == 0x123){

                //移动 -5到5 的距离
                int changeX = (int)( Math.random() * 5)*2 -5;
                int changeY = (int)(Math.random()*5)*2 - 5;
                //蝴蝶的新位置
                float newX = ivCurX + changeX;
                float newY = ivCurY + changeY;

                //移动蝴蝶
                TranslateAnimation translateAnimation = new TranslateAnimation(ivCurX,newX,ivCurY,newY);
                translateAnimation.setFillAfter(true); //保留动画结果
                translateAnimation.setDuration(200);
                iv.startAnimation(translateAnimation); //开始飞
                //更新蝴蝶位置
                ivCurX = newX;
                ivCurY = newY;
            }
        }
    };

    /**
     * 开始动画
     */
    public boolean onStart(View v){
        animationDrawable.stop();
        animationDrawable.start();
        //开始移动控件
        stopTimer();
        if(timerTask == null){
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(0x123);
                }
            };
        }
        tmrTranslate.schedule(timerTask,0,200);
        return true;
    }

    /**
     * 结束动画
     */
    public boolean onStop(View v){
        animationDrawable.stop();
        stopTimer();
        return true;
    }

    /**
     * 停止定时器
     */
    private void stopTimer(){
        if(timerTask != null){
            timerTask.cancel();
            timerTask = null;
        }
    }

 

动画xml文件



    
    
    
    
    
    


你可能感兴趣的:(android动画)