Android動畫控制項之Animation
概述:
android的動畫效果包括:移動,漸層透明度,旋轉,縮放。
實現動畫的方式有兩種:在java代碼中動態實現,在xml中靜態實現。
demo
動態實現:
/* 動畫的透明度漸層 */ AlphaAnimation alphaAnimation = new AlphaAnimation(1f,0);//透明度從1到0 alphaAnimation.setDuration(1000);//完成漸層的時間 alphaAnimation.setStartOffset(200);//回應時間 mImageViewAnim.startAnimation(alphaAnimation);//用一個ImageView載入animation,Image務必放入src或者載入過background /* 動畫的移動 */ TranslateAnimation translateAnimation = //從一個座標到另一個座標的移動,參數依次為:起始點橫、縱座標,結束點橫、縱座標 new TranslateAnimation(-mImageViewAnim.getMeasuredWidth(),0,0,0); translateAnimation.setDuration(1000); translateAnimation.setStartOffset(200); mImageViewAnim.startAnimation(translateAnimation); /* 動畫的旋轉 */ RotateAnimation rotateAnimation = new RotateAnimation(0,360);//預設沿著左上方旋轉 rotateAnimation.setDuration(1000); rotateAnimation.setStartOffset(200); mImageViewAnim.startAnimation(rotateAnimation); /* 動畫的縮放 */ ScaleAnimation scaleAnimation = new ScaleAnimation(1f,2f,1f,2f);//水平尺寸變化,豎直尺寸變化 scaleAnimation.setDuration(1000); scaleAnimation.setStartOffset(200); mImageViewAnim.startAnimation(scaleAnimation);
動畫的合併載入,需要一個AnimationSet,將所有的animation載入進去:
/** * 聲明一個AnimationSet,是一個儲存animation的集合 * false:被此set載入的每個animation用自己的interpolator; * true:所有animation功用一個interpolator */ AnimationSet animationSet = new AnimationSet(false); AlphaAnimation alphaAnimation = new AlphaAnimation(1f,0); TranslateAnimation translateAnimation = new TranslateAnimation(0,0,mImageViewAnim.getMeasuredWidth(),mImageViewAnim.getMeasuredHeight()); RotateAnimation rotateAnimation = new RotateAnimation(0,360,RotateAnimation.RELATIVE_TO_SELF ,0.5f,RotateAnimation.RELATIVE_TO_SELF ,0.5f);//RELATIVE_TO_SELF的意思是位置相對於自己 ScaleAnimation scaleAnimation = new ScaleAnimation(1f,2f,1f,2f); alphaAnimation.setDuration(1000); translateAnimation.setDuration(1000); rotateAnimation.setDuration(1000); scaleAnimation.setDuration(1000); //添加各個動畫 animationSet.addAnimation(alphaAnimation); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(rotateAnimation); animationSet.addAnimation(scaleAnimation); mImageViewAnim.startAnimation(animationSet);
這樣啟動並執行效果就是所有動畫組合咋一起的效果。
動畫的靜態載入,需要在res目錄下建立一個檔案夾anim,在裡面建立一個資源檔,我的叫rotation.xml
在java代碼中調用這個資源:
AnimationUtils utils = new AnimationUtils(); Animation animation = utils.loadAnimation(getApplicationContext(),R.anim.rotation); mImageViewAnim.startAnimation(animation);
啟動並執行效果是幾種xml中幾種動畫的綜合。