編輯:關於 Android 開發
偶然看到一款粒子爆炸效果的元件,視覺表現相當搶眼。但翻過原始碼後發現擴充性不佳:想換一種爆炸風格,得改動的地方多且散亂。於是我做了一輪重構,把「爆炸流程」與「粒子運動」兩件事拆開,讓替換效果變成替換一個類這麼簡單。
效果如下:


四個核心角色:
想要哪種爆炸效果,就給 ExplosionField 傳入對應的 ParticleFactory:
ExplosionField explosionField = new ExplosionField(this, new FallingParticleFactory());
再為需要效果的 View 註冊監聽:
explosionField.addListener(findViewById(R.id.text));
explosionField.addListener(findViewById(R.id.layout1));
注意:若傳入的是 ViewGroup,它會為其中的每個子 View 都加上爆炸效果。
public static Bitmap createBitmapFromView(View view) {
view.clearFocus();
Bitmap bitmap = createBitmapSafely(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888, 1);
if (bitmap != null) {
synchronized (sCanvas) {
Canvas canvas = sCanvas;
canvas.setBitmap(bitmap);
view.draw(canvas);
canvas.setBitmap(null);
}
}
return bitmap;
}
public static Bitmap createBitmapSafely(int width, int height,
Bitmap.Config config, int retryCount) {
try {
return Bitmap.createBitmap(width, height, config);
} catch (OutOfMemoryError e) {
e.printStackTrace();
if (retryCount > 0) {
System.gc();
return createBitmapSafely(width, height, config, retryCount - 1);
}
return null;
}
}
關鍵概念:Bitmap 可以視為一個像素矩陣,矩陣上每個點就是一個帶顏色的像素。只要能取出每個取樣點的顏色與座標,就能組裝成一個名為 Particle 的物件——粒子於是有顏色、有位置了。
createBitmapSafely 的重試機制是為了對抗 OOM:記憶體不足時先觸發 GC 再重試,重試次數遞減,避免無限遞迴。
public abstract class ParticleFactory {
public abstract Particle[][] generateParticles(Bitmap bitmap, Rect bound);
}
以最簡單的「下落」效果為例:
public class FallingParticleFactory extends ParticleFactory {
public static final int PART_WH = 8; // 預設粒子寬高
public Particle[][] generateParticles(Bitmap bitmap, Rect bound) {
int w = bound.width();
int h = bound.height();
int partW_Count = w / PART_WH; // 橫向個數
int partH_Count = h / PART_WH; // 豎向個數
int bitmap_part_w = bitmap.getWidth() / partW_Count;
int bitmap_part_h = bitmap.getHeight() / partH_Count;
Particle[][] particles = new Particle[partH_Count][partW_Count];
for (int row = 0; row < partH_Count; row++) {
for (int column = 0; column < partW_Count; column++) {
int color = bitmap.getPixel(column * bitmap_part_w, row * bitmap_part_h);
float x = bound.left + PART_WH * column;
float y = bound.top + PART_WH * row;
particles[row][column] = new FallingParticle(color, x, y, bound);
}
}
return particles;
}
}
邏輯很單純:bound 代表原 View 的寬高,依設定的粒子尺寸就能算出需要幾顆粒子鋪滿畫面,再逐一取出該位置的顏色來生成粒子。PART_WH 越小,粒子越細密、視覺越精緻,但效能負擔也越高。
爆炸需要一個繪製平台。做法是往 Activity 的根布局掛上一個全螢幕的 ExplosionField:
public class ExplosionField extends View {
/** 為 Activity 加上全螢幕覆蓋的 ExplosionField */
private void attach2Activity(Activity activity) {
ViewGroup rootView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
rootView.addView(this, lp);
}
}
收到點擊後,先播放一段震動預備動畫:
public void explode(final View view) {
// 防止重複點擊
if (explosionAnimatorsMap.get(view) != null
&& explosionAnimatorsMap.get(view).isStarted()) {
return;
}
// 取得 view 相對於整個螢幕的座標
final Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
int contentTop = ((ViewGroup) getParent()).getTop();
Rect frame = new Rect();
((Activity) getContext()).getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
rect.offset(0, -contentTop - statusBarHeight); // 扣除狀態列與標題列高度
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f).setDuration(150);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
Random random = new Random();
@Override
public void onAnimationUpdate(ValueAnimator animation) {
view.setTranslationX((random.nextFloat() - 0.5f) * view.getWidth() * 0.05f);
view.setTranslationY((random.nextFloat() - 0.5f) * view.getHeight() * 0.05f);
}
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
explode(view, rect); // 接著播放爆炸動畫
}
});
animator.start();
}
震動的做法是在 X、Y 兩個方向上隨機產生小幅位移,讓 View 看起來在顫抖。動畫結束後接續真正的爆炸:
private void explode(final View view, Rect rect) {
final ExplosionAnimator animator = new ExplosionAnimator(
this, Utils.createBitmapFromView(view), rect, mParticleFactory);
explosionAnimators.add(animator);
explosionAnimatorsMap.put(view, animator);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
// 原 View 縮小並淡出
view.animate().setDuration(150).scaleX(0f).scaleY(0f).alpha(0f).start();
}
@Override
public void onAnimationEnd(Animator animation) {
view.animate().alpha(1f).setDuration(150).start();
explosionAnimators.remove(animation);
explosionAnimatorsMap.remove(view);
}
});
animator.start();
}
ExplosionAnimator 本身:
public class ExplosionAnimator extends ValueAnimator {
public ExplosionAnimator(View view, Bitmap bitmap, Rect bound,
ParticleFactory particleFactory) {
mParticleFactory = particleFactory;
mPaint = new Paint();
mContainer = view;
setFloatValues(0.0f, 1.0f);
setDuration(DEFAULT_DURATION);
mParticles = mParticleFactory.generateParticles(bitmap, bound);
}
public void draw(Canvas canvas) {
if (!isStarted()) return;
for (Particle[] particle : mParticles) {
for (Particle p : particle) {
p.advance(canvas, mPaint, (Float) getAnimatedValue());
}
}
mContainer.invalidate();
}
@Override
public void start() {
super.start();
mContainer.invalidate();
}
}
結構非常乾淨:它是一個 ValueAnimator,在固定時間內從 0 數到 1;每個 frame 呼叫 draw(),把當前數值傳給每顆粒子的 advance()。粒子位置完全由粒子自己決定,與整體流程無關——這就是重構後最大的收益。
public class FallingParticle extends Particle {
static Random random = new Random();
float radius = FallingParticleFactory.PART_WH;
float alpha = 1.0f;
Rect mBound;
public FallingParticle(int color, float x, float y, Rect bound) {
super(color, x, y);
mBound = bound;
}
protected void caculate(float factor) {
cx = cx + factor * random.nextInt(mBound.width()) * (random.nextFloat() - 0.5f);
cy = cy + factor * random.nextInt(mBound.height() / 2);
radius = radius - factor * random.nextInt(2);
alpha = (1f - factor) * (1 + random.nextFloat());
}
}
讀懂這段就懂了下落效果的秘密:cy 持續增加(往下掉),cx 隨機增減(左右飄移),radius 逐漸變小、alpha 逐漸降低(越掉越淡)。最後把自己畫出來:
protected void draw(Canvas canvas, Paint paint) {
paint.setColor(color);
paint.setAlpha((int) (Color.alpha(color) * alpha));
canvas.drawCircle(cx, cy, radius, paint);
}
整篇文章的結論就一句:要新增爆炸風格,只需寫一個 Particle 子類實作自己的 caculate(),再寫一個對應的 ParticleFactory。 ExplosionField 與 ExplosionAnimator 完全不用動。
舉例來說,想要「四散噴射」效果,就让 cx 與 cy 依同一夾角但不同速度向外位移;想要「火燒」效果,讓 cy 隨時間遞減並讓顏色偏向紅黃漸層即可。流程層完全不必得知。
用 ListView 搭配 ViewPager 打造新聞 App 首頁
用 ListView 搭配 ViewPager 打造新聞 App 首頁 成品預覽 這次要實作的是一個類似新聞 App 的資訊流首頁:頂端是一張可自動輪播的大圖(用 Vi
Android 屬性動畫入門:ValueAnimator、ObjectAnimator 與組合動畫
Android 屬性動畫入門:ValueAnimator、ObjectAnimator 與組合動畫 Android 動畫體系中,屬性動畫是相當重要的成員。與傳統補間動畫相
SharedPreferences 實作:在 Fragment 裡保存表單輸入內容
SharedPreferences 實作:在 Fragment 裡保存表單輸入內容 SharedPreferences 是 Android 提供的輕量級鍵值存儲方案,特別
WebView 混合開發:Java 與 JavaScript 雙向調用實戰
WebView 混合開發:Java 與 JavaScript 雙向調用實戰 在實際項目中,考慮開發效率與界面迭代速度,經常會用 WebView 加 H5 頁面來承載部分業