原理以後再說,主要使用android的camera實現
實現動畫的類後面再給出來,先上使用代碼,體現一下這東西使用有多麼容易
代碼的功能:點擊這個ID爲hello的textView,它就開始3D翻轉
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".StartActivity">
<TextView
android:id="@+id/hello"
android:text="@string/hello_world"
android:background="#FFFF00FF"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
StartActivity.java
public class StartActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
initView();
initListener();
}
private void initListener() {
textView.setOnClickListener(this);
}
private void initView() {
textView = (TextView) findViewById(R.id.hello);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.hello :
Rotate3dAnimation rotate3dAnimation = new Rotate3dAnimation(view.getWidth(), view.getHeight(), -90, 90);
rotate3dAnimation.setDuration(1000);
textView.startAnimation(rotate3dAnimation);
break;
}
}
}
最後是實現動畫的類
public class Rotate3dAnimation extends Animation {
private int centerX, centerY;
private int width, height;
private float startDegree, endDegree;
{
centerX = 0 ;
centerY = 0 ;
}
public Rotate3dAnimation(int w, int h, float startDegree, float endDegree) {
this.width = w;
this.height = h;
this.centerX = w>>1;
this.centerY = h >> 1;
this.startDegree = startDegree;
this.endDegree = endDegree;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int translateX = 0 ;
int translateZ = 0 ;
int translateY = 0;
double a = (endDegree - startDegree) * interpolatedTime + startDegree + 90;
// Log.d("3d", endDegree + "");
// Log.d("3d", startDegree + "");
// Log.d("3d", Math.cos(a) + "");
//Math.cos是弧度制的
translateX = (int) (- (width >> 1) * Math.cos(a * 3.1415926 / 180));
translateZ = (int) (- (width >> 1) * Math.sin(a * 3.1415926 / 180 ) + (width >> 1 ));
Matrix matrix = t.getMatrix();
Camera camera = new Camera();
camera.save();
camera.translate(0,0,translateZ);
camera.rotateY(startDegree + (endDegree - startDegree) * interpolatedTime);
camera.getMatrix(matrix);
camera.restore();
//設置旋轉的中心點
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
matrix.postTranslate(translateX,translateY);
}
}