編輯:關於 Android 程式設計
要讓 View 產生 3D 翻轉的錯覺,核心原理只有兩點:讓它繞 Y 軸旋轉,同時在 Z 軸方向做一次進出動畫(translation),營造出「靠近又遠離」的景深。示範程式的重點在於自訂動畫類別,以及在動畫結束時切換兩個重疊的 ImageView。
先來看運行成果:
繼承 Animation,覆寫 applyTransformation()。這個方法會在每一格影格被呼叫,interpolatedTime 是 0~1 的進度值。我們用它算出當前角度,再透過 Camera 取得旋轉後的 Matrix,塞進 Transformation 物件裡。
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final Matrix matrix = t.getMatrix();
camera.save();
if (mReverse) {
camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
} else {
camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
}
camera.rotateY(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
這是最多人卡住的地方:
matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY);
原因是 Camera 拿到的旋轉矩陣,是「以原點為中心」進行旋轉的。如果直接把這個矩陣套到 View 上,View 就會繞著自己左上角的 (0, 0) 翻過去,看起來像是往畫面外側甩出去。
解法是做一次座標系搬移:先用 preTranslate 把 View 的左上角移到原點(也就是把旋轉中心對齊到原點),套用旋轉矩陣,再用 postTranslate 把它搬回原本的位置。pre 與 post 的順序不能對調——Matrix 的 pre 是「先套用右邊的」,post 是「後套用右邊的」,兩者語意剛好相反,寫錯就會得到完全不同的結果。
版面把兩張同尺寸的 ImageView 疊在同一個 FrameLayout 裡,位置重疊。做法是先對最上層那張播放 0° → 90° 的動畫,等它轉到側面看不見時,切換顯示/隱藏,再對另一張播放 90° → 180°,如此循環。
動畫監聽器負責在動畫結束時拋出切換動作:
private final class DisplayNextView implements Animation.AnimationListener {
public void onAnimationStart(Animation animation) { }
public void onAnimationEnd(Animation animation) {
// 容器轉到 90 度時看不見,正好在這一刻交換兩張圖
mContainer.post(new SwapViews());
}
public void onAnimationRepeat(Animation animation) { }
}
切換的實際邏輯:
private final class SwapViews implements Runnable {
@Override
public void run() {
mImageView1.setVisibility(View.GONE);
mImageView2.setVisibility(View.GONE);
mIndex++;
if (0 == mIndex % 2) {
mStartAnimView = mImageView1;
} else {
mStartAnimView = mImageView2;
}
mStartAnimView.setVisibility(View.VISIBLE);
mStartAnimView.requestFocus();
Rotate3dAnimation rotation = new Rotate3dAnimation(
-90, 0, mCenterX, mCenterY, mDepthZ, false);
rotation.setDuration(mDuration);
rotation.setFillAfter(true);
rotation.setInterpolator(new DecelerateInterpolator());
mStartAnimView.startAnimation(rotation);
}
}
啟動動畫的方法,這裡把 mReverse 傳 true,讓它「遠離再靠近」:
private void applyRotation(View animView, float startAngle, float toAngle) {
float centerX = mCenterX;
float centerY = mCenterY;
Rotate3dAnimation rotation = new Rotate3dAnimation(
startAngle, toAngle, centerX, centerY, mDepthZ, true);
rotation.setDuration(mDuration);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView());
animView.startAnimation(rotation);
}
點擊按鈕時先算出中心點與 Z 軸深度,再啟動動畫:
@Override
public void onClick(View v) {
mCenterX = mContainer.getWidth() / 2;
mCenterY = mContainer.getHeight() / 2;
getDepthZ();
applyRotation(mStartAnimView, 0, 90);
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Do 3d animation" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20px"
android:text="Input Depth on Z axis. [0, 300]" />
<EditText
android:id="@+id/edit_depthz"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="0"/>
<FrameLayout
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="20dp"
android:src="@drawable/f" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="20dp"
android:src="@drawable/s"
android:visibility="gone"/>
</FrameLayout>
</LinearLayout>
package com.nj1s.lib.anim;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* 讓 View 繞 Y 軸在兩個角度之間旋轉,並在 Z 軸(景深)方向加入位移以強化立體感。
*/
public class Rotate3dAnimation extends Animation {
private final float mFromDegrees;
private final float mToDegrees;
private final float mCenterX;
private final float mCenterY;
private final float mDepthZ;
private final boolean mReverse;
private Camera mCamera;
public Rotate3dAnimation(float fromDegrees, float toDegrees,
float centerX, float centerY,
float depthZ, boolean reverse) {
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mCenterX = centerX;
mCenterY = centerY;
mDepthZ = depthZ;
mReverse = reverse;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final Matrix matrix = t.getMatrix();
camera.save();
if (mReverse) {
camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
} else {
camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
}
camera.rotateY(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
public class Rotate3dAnimActivity extends Activity {
ImageView mImageView1 = null;
ImageView mImageView2 = null;
ImageView mStartAnimView = null;
View mContainer = null;
int mDuration = 500;
float mCenterX = 0.0f;
float mCenterY = 0.0f;
float mDepthZ = 0.0f;
int mIndex = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rotate_anim);
mImageView1 = (ImageView) findViewById(R.id.imageView1);
mImageView2 = (ImageView) findViewById(R.id.imageView2);
mContainer = findViewById(R.id.container);
mStartAnimView = mImageView1;
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCenterX = mContainer.getWidth() / 2;
mCenterY = mContainer.getHeight() / 2;
getDepthZ();
applyRotation(mStartAnimView, 0, 90);
}
});
InputMethodManager imm =
(InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
getWindow().getDecorView().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void getDepthZ() {
EditText editText = (EditText) findViewById(R.id.edit_depthz);
String string = editText.getText().toString();
try {
mDepthZ = (float) Integer.parseInt(string);
} catch (Exception e) {
e.printStackTrace();
}
}
private void applyRotation(View animView, float startAngle, float toAngle) {
Rotate3dAnimation rotation = new Rotate3dAnimation(
startAngle, toAngle, mCenterX, mCenterY, mDepthZ, true);
rotation.setDuration(mDuration);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView());
animView.startAnimation(rotation);
}
private final class DisplayNextView implements Animation.AnimationListener {
public void onAnimationStart(Animation animation) { }
public void onAnimationEnd(Animation animation) {
mContainer.post(new SwapViews());
}
public void onAnimationRepeat(Animation animation) { }
}
private final class SwapViews implements Runnable {
@Override
public void run() {
mImageView1.setVisibility(View.GONE);
mImageView2.setVisibility(View.GONE);
mIndex++;
mStartAnimView = (0 == mIndex % 2) ? mImageView1 : mImageView2;
mStartAnimView.setVisibility(View.VISIBLE);
mStartAnimView.requestFocus();
Rotate3dAnimation rotation = new Rotate3dAnimation(
-90, 0, mCenterX, mCenterY, mDepthZ, false);
rotation.setDuration(mDuration);
rotation.setFillAfter(true);
rotation.setInterpolator(new DecelerateInterpolator());
mStartAnimView.startAnimation(rotation);
}
}
}
把 mReverse 拿來對照,就能看出它的作用:true 時 Z 軸位移隨時間增加(由遠而近),false 時隨時間遞減(由近而遠)。順著這個邏輯調整 duration 與 interpolator,同一套類別就能做出翻牌、卡片切換、封面翻轉等多種效果。
Android 自定義時鐘指針
自定義時鐘是指針類 View 中很經典的練習題。透過它,可以熟悉 Canvas 繪圖、Paint 設定、角度計算與定時刷新等技巧。拆解需求一個時鐘可以拆成幾個部分:1.
Java 4 Android 開發教程(四):變數
變數是程式語言裡最基本的儲存單位。本文說明變數的定義、宣告語法、型別與命名規範。 什麼是變數 變數用來在程式中儲存資訊。宣告變數時,等於告訴編譯器「我要用這個名字、這個
取得 Android 設備已安裝應用清單:名稱、套件名與圖示
本文示範如何取得設備中已安裝的應用資訊,包含應用名稱、套件名稱、圖示等,並在清單中點選任一項時直接啟動對應的應用。 一、程式碼實作 package com.exampl
Android 進程保活機制與常見方案解析
Android 應用常希望提升進程存活能力,以降低被系統或管理工具回收的概率,並在進程結束後重新啟動。本文從進程優先級、內存回收機制與常見拉活方案三個方面進行整理。需要說