編輯:Android 開發實例
想要讓一張圖片沿著弧形軌跡飛出去(例如購物車拋物線加入動畫),關鍵其實回到高中數學:先求出拋物線方程,再把 x 與 y 的關係拆成兩組 keyframe 交給 ObjectAnimator。
已知平面上任意三點即可確定一條拋物線。以圖中的例子為例:

設 y = ax² + bx + c,並取 A1(0,0)、A2(300,0)、A3(150,300) 代入聯立求解,可得:
y = -1/75 x² + 4x
有了這個式子,x 與 y 的對應關係就定了,剩下的只是把數值餵給動畫框架。
把整段位移切成 300 個 keyframe,讓 X 軸等速推進、Y 軸依方程取值,兩個 PropertyValuesHolder 一起播放即可。
// 以 300 步完成整段位移
final int count = 300;
/**
* 啟動指定 ImageView 的拋物線動畫
*/
private void startAnimation(final ImageView imageView) {
Keyframe[] keyframes = new Keyframe[count];
final float keyStep = 1f / (float) count;
// X 軸:線性推進
float key = keyStep;
for (int i = 0; i < count; ++i) {
keyframes[i] = Keyframe.ofFloat(key, i + 1);
key += keyStep;
}
PropertyValuesHolder pvhX = PropertyValuesHolder.ofKeyframe("translationX", keyframes);
// Y 軸:代入拋物線方程
key = keyStep;
for (int i = 0; i < count; ++i) {
keyframes[i] = Keyframe.ofFloat(key, -getY(i + 1));
key += keyStep;
}
PropertyValuesHolder pvhY = PropertyValuesHolder.ofKeyframe("translationY", keyframes);
ObjectAnimator yxBouncer =
ObjectAnimator.ofPropertyValuesHolder(imageView, pvhY, pvhX)
.setDuration(1500);
yxBouncer.setInterpolator(new BounceInterpolator());
yxBouncer.start();
}
final float a = -1f / 75f;
/**
* 依方程式計算拋物線的 y 值
* 對應已知三點 (0,0)、(300,0)、(150,300)
*/
private float getY(float x) {
return a * x * x + 4 * x;
}
呼叫時只要一行:startAnimation(imageView);。Y 值取負號是因為螢幕座標軸向下,需要翻正。若想要更自然的落體感,把 BounceInterpolator 換成 AccelerateInterpolator 或 DecelerateInterpolator 即可。
如果三點不是這麼剛好對稱,可以用下面這支程式把 a、b、c 算出來,再把結果填回 getY()。
package com.freesonfish;
public class ParabolaAlgorithm {
public static void main(String[] args) {
final float[][] points = { { 6, 15 }, { 15, 70 }, { 40, 60 } };
calculate(points);
}
/**
* a = (y1*(x2-x3) + y2*(x3-x1) + y3*(x1-x2))
* / (x1²*(x2-x3) + x2²*(x3-x1) + x3²*(x1-x2))
* b = (y1-y2)/(x1-x2) - a*(x1+x2)
* c = y1 - x1²*a - x1*b
*/
private static void calculate(float[][] points) {
float x1 = points[0][0], y1 = points[0][1];
float x2 = points[1][0], y2 = points[1][1];
float x3 = points[2][0], y3 = points[2][1];
final float a = (y1 * (x2 - x3) + y2 * (x3 - x1) + y3 * (x1 - x2))
/ (x1 * x1 * (x2 - x3) + x2 * x2 * (x3 - x1) + x3 * x3 * (x1 - x2));
final float b = (y1 - y2) / (x1 - x2) - a * (x1 + x2);
final float c = y1 - (x1 * x1) * a - x1 * b;
System.out.println("-a->" + a + " b->" + b + " c->" + c);
}
}
最後提醒:keyframe 數量會直接影響效能,300 個 frame 在舊機型上可能會卡,實測後可視情況降到 60~120 個,視覺上幾乎看不出差別。
Android MediaPlayer 範例:建立可控制音訊的播放器
這個範例會建立一個可播放、暫停、快轉與快退的音訊播放器。畫面中會包含播放控制按鈕、時間顯示與 SeekBar 進度條。 使用 raw 資源 將 song.mp3 放入 r
Android ApiDemo 系列三:Activity 切換動畫
ApiDemo 的 Animation 範例示範在切換 Activity 時加入動畫效果。常見的兩種效果是淡入與縮放:淡入讓新畫面由透明逐漸顯示,縮放則讓新畫面由小變大出
深入淺析 Android Fragment(下篇):回退堆疊、通訊與旋轉重建
上篇談了 Fragment 的由來、生命週期、靜態與動態使用,以及 FragmentTransaction 的常用方法。這篇接著處理更實際的問題:回退堆疊怎麼管、Frag
Android 自定義權限的實作方式
自定義權限是 Android 組件保護的重要機制。透過自定義權限,開發者可限制特定 Activity、Service 或其他組件只能被持有指定權限的應用呼叫。定義權限的應