Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中 View 炸裂特效的實現原理詳解

編輯:關於 Android 程式設計

本文實例講述了 Android 中 View 炸裂特效的實現方法,分享給大家參考。

前幾天微博上被一個非常優秀的 Android 開源組件刷屏了——ExplosionField,效果十分酷炫,有點類似 MIUI 卸載 APP 時的動畫。它不僅效果拉風,代碼也寫得相當出色,讓人忍不住要拿來仔細研讀一番。

創建 ExplosionField

ExplosionField 繼承自 View,在 onDraw 方法中繪制動畫特效。它提供了一個 attach2Window 方法,可以把 ExplosionField 作為一個子 View 添加到 Activity 的根視圖中:

 public static ExplosionField attach2Window(Activity activity) { ViewGroup rootView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT); ExplosionField explosionField = new ExplosionField(activity); rootView.addView(explosionField, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return explosionField; } 

由於 explosionField 的 LayoutParams 都被設置為 MATCH_PARENT,這樣一來,一個 View 炸裂出來的粒子就能繪制在整個 Activity 區域內。這裡有個小知識點:可以用 Window.ID_ANDROID_CONTENT 來替代 android.R.id.content。

炸裂之前的震動效果

在 View 的點擊事件中調用 mExplosionField.explode(v) 之後,View 會先震動,然後再炸裂。震動效果的實現比較簡單:設定一個 [0, 1] 區間的 ValueAnimator,在 onAnimationUpdate 中隨機平移 x 和 y 坐標,最後把 scale 和 alpha 動態減為 0:

 int startDelay = 100; 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.start(); view.animate().setDuration(150).setStartDelay(startDelay).scaleX(0f).scaleY(0f).alpha(0f).start(); 

根據 View 創建 Bitmap

震動結束後就開始最關鍵的炸裂,炸裂是與隱藏同時進行的。先看炸裂的 API:

void explode(Bitmap bitmap, Rect bound, long startDelay, long duration)

前兩個參數 bitmap 和 bound 是關鍵。如果 View 本身就是一個 ImageView,且它的 Drawable 是 BitmapDrawable,那就可以直接獲取這個 Bitmap:

 if (view instanceof ImageView) { Drawable drawable = ((ImageView) view).getDrawable(); if (drawable != null && drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } } 

如果不是 ImageView,則按以下步驟創建 bitmap:新建 Canvas → 根據 View 大小創建空 bitmap → 把空 bitmap 設為 Canvas 底布 → 把 View 繪制到 canvas 上 → 最後把 canvas 的 bitmap 設為 null。繪制前記得清掉 View 焦點,因為焦點可能改變 View 的 UI 狀態:

 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); } } 

這裡的 sCanvas 是一個靜態變量,可以節省每次創建時的開銷。而作者創建位圖的函數 createBitmapSafely 尤其巧妙——如果新建 Bitmap 時發生 OOM,就主動調用一次 System.gc() 然後重試,這個重試機制展現了扎實的功底:

 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; } } 

另一個重要參數 bound 的創建相對簡單:

 Rect r = new Rect(); view.getGlobalVisibleRect(r); int[] location = new int[2]; getLocationOnScreen(location); r.offset(-location[0], -location[1]); r.inset(-mExpandInset[0], -mExpandInset[1]); 

先獲取待炸裂 View 的全局可視區域 Rect r,再通過 getLocationOnScreen 獲取 ExplosionField 在屏幕中的坐標,據此把可視區域平移,這樣炸裂效果才會正確顯示在 ExplosionField 中,最後再按 mExpandInset 值(默認為 0)擴展一下。

創建粒子

炸裂成粒子的方法全貌如下:

 public void explode(Bitmap bitmap, Rect bound, long startDelay, long duration) { final ExplosionAnimator explosion = new ExplosionAnimator(this, bitmap, bound); explosion.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mExplosions.remove(animation); } }); explosion.setStartDelay(startDelay); explosion.setDuration(duration); mExplosions.add(explosion); explosion.start(); } 

這裡用一個容器類變量 mExplosions 來保存 ExplosionAnimator,是因為 Activity 中多個 View 的炸裂動畫可能需要同時進行,所以要為每個 View 對應的動畫各保存一份,動畫結束後再刪除。

作者自定義了繼承自 ValueAnimator 的 ExplosionAnimator,它主要做兩件事:創建粒子(generateParticle)和繪制粒子(draw)。在構造函數中,它把 bitmap 劃分成 17×17 的矩陣,取每個單元格中心位置的像素值來生成一個 15×15 的粒子矩陣:

 public ExplosionAnimator(View container, Bitmap bitmap, Rect bound) { mPaint = new Paint(); mBound = new Rect(bound); int partLen = 15; mParticles = new Particle[partLen * partLen]; Random random = new Random(System.currentTimeMillis()); int w = bitmap.getWidth() / (partLen + 2); int h = bitmap.getHeight() / (partLen + 2); for (int i = 0; i < partLen; i++) { for (int j = 0; j < partLen; j++) { mParticles[(i * partLen) + j] = generateParticle(bitmap.getPixel((j + 1) * w, (i + 1) * h), random); } } mContainer = container; setFloatValues(0f, END_VALUE); setInterpolator(DEFAULT_INTERPOLATOR); setDuration(DEFAULT_DURATION); } 

最巧妙的莫過於它的 draw 方法:

 public boolean draw(Canvas canvas) { if (!isStarted()) { return false; } for (Particle particle : mParticles) { particle.advance((float) getAnimatedValue()); if (particle.alpha > 0f) { mPaint.setColor(particle.color); mPaint.setAlpha((int) (Color.alpha(particle.color) * particle.alpha)); canvas.drawCircle(particle.cx, particle.cy, particle.radius, mPaint); } } mContainer.invalidate(); return true; } 

一開始我很困惑:既然繪制粒子是在 ExplosionField 的 onDraw 中進行,那勢必需要不停刷新,但作者並不是這麼做的,實現方式令人驚艷。首先,作者在 ExplosionAnimator 中重載了 start() 方法,通過 mContainer.invalidate(mBound) 只刷新待炸裂 View 對應的區塊:

 @Override public void start() { super.start(); mContainer.invalidate(mBound); } 

而 mContainer 就是鋪滿整個 Activity 的 ExplosionField,它的 onDraw 又會調用 ExplosionAnimator 的 draw 方法:

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (ExplosionAnimator explosion : mExplosions) { explosion.draw(canvas); } } 

如此便形成了一個遞歸:兩者相互調用、不斷刷新,直到所有粒子的 alpha 值都變為 0,刷新才停止。這種設計既保證了動畫的流暢,又避免了不必要的全屏刷新開銷。

總結

這個開源庫的代碼質量相當高,設計思路也很值得學習,十分佩服作者。希望本文所述對大家進行 Android 開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved