摘要:Android animation example: rotate 旋轉效果
使用RotateAnumation來模擬旋轉轉盤效果,
//首先隨機取得小於360度旋轉角度
int stop = (int)(Math.random() * 360);
// 加入 3600度讓動畫旋轉效果明顯,同時也不會改變random的值
Animation am = new RotateAnimation(0f, stop + 3600,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
am.setAnimationListener(MainActivity.this);
am.setDuration(3000);
//動畫結束後,保持旋轉後的狀態
am.setFillAfter(true);
mImage.startAnimation(am);
從上例加入機率分配效果
機率分配如下:
選項 | 角度 | 範圍 | 機率 |
A | 0 | x < 5 | 5% |
B | 60 | 5 <= x < 15 | 10% |
C | 120 | 15 <= x < 30 | 15% |
D | 180 | 30 <= x < 45 | 15% |
E | 240 | 45 <= x < 65 | 20% |
F | 300 | 65 <= x < 100 | 35% |
Demo:
程式:
public class MainActivity extends Activity implements Animation.AnimationListener{
private final String TAG = MainActivity.this.getClass().getSimpleName();
private ImageView mImage;
private int stop = 0;
private int result = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImage = (ImageView) findViewById(R.id.iv_circle);
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stop = (int)(Math.random() * 100);
Log.d(TAG, "Stop = " + stop);
result = prosibility(stop);
Log.d(TAG, "After prosibility: temp = " + result);
Animation am = new RotateAnimation(0f, 3600 + result,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
am.setAnimationListener(MainActivity.this);
am.setDuration(3000);
am.setFillAfter(true);
mImage.startAnimation(am);
}
});
}
private int prosibility(int stop) {
if(stop < 5) {
return 360;
} else if(5 <= stop && stop < 15) {
return 300;
} else if(15 <= stop && stop < 30) {
return 240;
} else if(30 <= stop && stop < 45) {
return 180;
} else if(45 <= stop && stop < 65) {
return 120;
} else if(65 <= stop && stop < 100) {
return 60;
} else {
Log.d(TAG, "Should be not here");
return 0;
}
}
@Override
public void onAnimationStart(Animation animation) {
Log.d(TAG, "onAnimationStart");
}
@Override
public void onAnimationEnd(Animation animation) {
Log.d(TAG, "onAnimationEnd");
String value = "";
if(stop < 5) {
value = "A";
} else if(5 <= stop && stop < 15) {
value = "B";
} else if(15 <= stop && stop < 30) {
value = "C";
} else if(30 <= stop && stop < 45) {
value = "D";
} else if(45 <= stop && stop < 65) {
value = "E";
} else if(65 <= stop && stop < 100) {
value = "F";
} else {
Log.d(TAG, "Should be not here");
}
Toast.makeText(MainActivity.this, "Result = " + value, Toast.LENGTH_SHORT).show();
}
@Override
public void onAnimationRepeat(Animation animation) {
Log.d(TAG, "onAnimationRepeat");
}
}