編輯:Android 資訊
閒逛時看到一款粒子爆炸控件,效果不錯,但代碼擴展性很差——想換一種爆炸效果,要改的地方太多。於是我把源碼重構了一遍,核心思路是把「爆炸流程」和「粒子怎麼動」徹底分開:前者固定,後者由演算法決定。
最終效果:


ExplosionField:爆炸發生的場地,本質是一個 View,覆蓋整個屏幕——只有這樣才能看到完整的爆炸效果。
ExplosionAnimator:爆炸動畫,本質是計時器,繼承自 ValueAnimator。在約 1 秒內從 0 走到 1,每次計時更新所有粒子的運動狀態。draw() 是最重要的方法,讓所有粒子重繪自身。
ParticleFactory:抽象類,負責生產粒子數組。不同實現產出不同風格的粒子。
Particle:抽象粒子類,必須擁有 cx、cy 坐標與 color 顏色,並實現兩個方法——draw() 決定怎麼畫自己(圓形、方形等),caculate() 依當前時間算出自己該在哪。
要換爆炸風格,只需換工廠:
ExplosionField explosionField = new ExplosionField(this, new FallingParticleFactory());
然後把需要爆炸的控件登記進來:
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,這個粒子就自帶顏色了。
public abstract class ParticleFactory {
public abstract Particle[][] generateParticles(Bitmap bitmap, Rect bound);
}以 gif 中第一個下落效果的工廠為例:
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 的寬高信息。設定了粒子尺寸之後,用控件尺寸一除就知道需要多少粒子鋪滿它,再逐個取色、取位,粒子就造好了。
public class ExplosionField extends View {
/** 給 Activity 加上全屏覆蓋的 ExplosionField */
private void attach2Activity(Activity activity) {
ViewGroup rootView = activity.findViewById(Window.ID_ANDROID_CONTENT);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
rootView.addView(this, lp);
}
}場地就位後響應點擊,先播一段震動:
/** 使該 view 爆破 */
public void explode(final View view) {
// 防止重複點擊
if (explosionAnimatorsMap.get(view) != null
&& explosionAnimatorsMap.get(view).isStarted()) {
return;
}
if (view.getVisibility() != View.VISIBLE || view.getAlpha() == 0) {
return;
}
// 為了正確繪製粒子
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 方向隨機給一點位移即可。震動結束後接上真正的爆炸:
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.animate().setDuration(150)
.scaleX(0f).scaleY(0f).alpha(0f).start();
}
@Override
public void onAnimationEnd(Animator animation) {
view.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(150).start();
explosionAnimators.remove(animation);
explosionAnimatorsMap.remove(view);
}
});
animator.start();
}爆炸動畫本體:
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;在 draw() 裡把當前進度傳給每個粒子的 advance(),而 advance() 內部又調用 draw() 與 caculate()。
也就是說,粒子在哪,完全由粒子自己決定,與流程無關。這正是解耦的價值所在。
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());
}
}caculate(float factor) 依當前時間推算下一個位置。這裡 cy 只增,cx 隨機增減,半徑與透明度遞減,下落感就出來了。算完位置,粒子把自己畫出來:
protected void draw(Canvas canvas, Paint paint) {
paint.setColor(color);
paint.setAlpha((int) (Color.alpha(color) * alpha));
canvas.drawCircle(cx, cy, radius, paint);
}結構擺在這裡,結論很清楚:流程不用動,你要做的只有兩件事——
換湯不換藥,特效卻完全是另一個模樣。這就是「流程與運動分離」帶來的紅利。
Android 全域變數與區域變數:一個 Adapter Bug 的誕生與修復
全域變數顧名思義,是在整個類別中、多個方法之間都能存取的變數,也稱外部變數;區域變數則只在特定的方法或程序區塊內有效。宣告一個變數很容易,但真正用對並不那麼理所當然。 我
Android 數據存儲的五大實現方式詳解
數據存儲是開發中使用頻率極高的環節。本文系統梳理 Android 平台上的五種存儲方式,並對比它們的用法與異同。 第一種:使用 SharedPreferences 存儲數
Android 運算效能優化:從 Traceview 到批次與快取
Android 應用效能不只取決於演算法本身,也與程式碼寫法、執行環境與資料處理方式有關。運算優化的重點,是找出耗時方法、減少重複計算,並避免阻塞主線程。 為什麼相同功能
以 MediaPlayer 為例,透視 Android Framework 層的 JNI 運作機制
JNI(Java Native Interface,本地呼叫介面)對寫 Java 的人來說不陌生,主要功能就兩項:讓 Java 層呼叫 C/C++,以及讓 C/C++ 回