翻轉(zhuǎn)硬幣實(shí)際上就是翻轉(zhuǎn)textview,眾所周知Android有個(gè)動(dòng)畫類Animation.Java变泄,RotateAnimation類繼承自該類,構(gòu)造函數(shù)需有三個(gè)參數(shù),分別說明動(dòng)畫組件的中心點(diǎn)位置及旋轉(zhuǎn)方向耗跛。
RotateAnimation.initialize()將初始化動(dòng)畫組件及其父容器的寬高;通常亦可進(jìn)行另外的初始化工作攒发,本例中用于執(zhí)行對(duì)camera進(jìn)行實(shí)例化賦值调塌。
RotateAnimation.applyTransformation()第一個(gè)參數(shù)為動(dòng)畫的進(jìn)度時(shí)間值,取值范圍為[0.0f,1.0f]惠猿,第二個(gè)參數(shù)Transformation記錄著動(dòng)畫某一幀中變形的原始數(shù)據(jù)羔砾。該方法在動(dòng)畫的每一幀顯示過程中都會(huì)被調(diào)用。
RotateAnimation.java具體代碼如下:
```
'public classRotateAnimation extends Animation {
/** 值為true時(shí)可明確查看動(dòng)畫的旋轉(zhuǎn)方向偶妖。 */
public static final booleanDEBUG =false;
/** 沿Y軸正方向看姜凄,數(shù)值減1時(shí)動(dòng)畫逆時(shí)針旋轉(zhuǎn)。 */
public static final booleanROTATE_DECREASE =true;
/** 沿Y軸正方向看趾访,數(shù)值減1時(shí)動(dòng)畫順時(shí)針旋轉(zhuǎn)态秧。 */
public static final booleanROTATE_INCREASE =false;
/** Z軸上最大深度。 */
public static final floatDEPTH_Z =310.0f;
/** 動(dòng)畫顯示時(shí)長(zhǎng)扼鞋。 */
public static final longDURATION =800l;
/** 圖片翻轉(zhuǎn)類型申鱼。 */
private final booleantype;
private final floatcenterX;
private final floatcenterY;
privateCamera camera;
/** 用于監(jiān)聽動(dòng)畫進(jìn)度。當(dāng)值過半時(shí)需更新txtNumber的內(nèi)容云头。 */
privateInterpolatedTimeListener listener;
publicRotateAnimation(floatcX,floatcY,booleantype) {
centerX = cX;
centerY= cY;
this.type = type;
setDuration(DURATION);
}
public voidinitialize(intwidth,intheight,intparentWidth,intparentHeight) {
// 在構(gòu)造函數(shù)之后捐友、getTransformation()之前調(diào)用本方法。
super.initialize(width, height, parentWidth, parentHeight);
camera =newCamera();
}
public voidsetInterpolatedTimeListener(InterpolatedTimeListener listener) {
this.listener = listener;
}
protected voidapplyTransformation(floatinterpolatedTime, Transformation transformation) {
// interpolatedTime:動(dòng)畫進(jìn)度值溃槐,范圍為[0.0f,10.f]
if(listener !=null) {
listener.interpolatedTime(interpolatedTime);
}
floatfrom =0.0f, to =0.0f;
if(type == ROTATE_DECREASE) {
from =0.0f;
to =180.0f;
}else if(type == ROTATE_INCREASE) {
from =360.0f;
to =180.0f;
}
floatdegree = from + (to - from) * interpolatedTime;
booleanoverHalf = (interpolatedTime >0.5f);
if(overHalf) {
// 翻轉(zhuǎn)過半的情況下匣砖,為保證數(shù)字仍為可讀的文字而非鏡面效果的文字,需翻轉(zhuǎn)180度昏滴。
degree = degree -180;
}
// float depth = 0.0f;
floatdepth = (0.5f- Math.abs(interpolatedTime -0.5f)) * DEPTH_Z;
finalMatrix matrix = transformation.getMatrix();
camera.save();
camera.translate(0.0f,0.0f, depth);
camera.rotateY(degree);
camera.getMatrix(matrix);
camera.restore();
if(DEBUG) {
if(overHalf) {
matrix.preTranslate(-centerX *2, -centerY);
matrix.postTranslate(centerX *2,centerY);
}
}else{
//確保圖片的翻轉(zhuǎn)過程一直處于組件的中心點(diǎn)位置
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX,centerY);
}
}
/** 動(dòng)畫進(jìn)度監(jiān)聽器猴鲫。 */
public? interfaceInterpolatedTimeListener {
public voidinterpolatedTime(floatinterpolatedTime);
}
}
```