編輯:關於 Android 程式設計
還記得天天果凍開機時那個相當吸睛的 Splash 動畫嗎?畫面中會有一個空心圓由中心逐漸向外擴散,仔細觀察還會發現,在圓圈擴散的過程中,Logo 本身也伴隨著漸變消失的效果。這類對幀率有一定要求的動畫,筆者強烈建議使用 SurfaceView 來繪製。我自己也試過直接重寫 View 的 onDraw 方法,結果在高解析度的 Android 手機上直接悲劇——卡頓到不行。
先來看看我們要還原的效果:

首先用 Android Studio 打開 React Native 專案中的 android 資料夾,新增 SplashScreen 與 SplashScreenPackage 兩個類別:

SplashScreen 繼承自 ReactContextBaseJavaModule,需要重寫 getName() 方法:
@Override
public String getName() {return "%JS調用類的名字%"; }
接著建立內部類 MySurfaceView,繼承 SurfaceView:
class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private Thread thread; // SurfaceView通常需要自己單獨的線程來播放動畫
private Canvas canvas;
private SurfaceHolder surfaceHolder;
public MySurfaceView(Context c) { super(c); this.surfaceHolder = this.getHolder(); this.surfaceHolder.addCallback(this); } @Override public void run() { if (!firstRun) { while (true) { if (radius > MaxRaduis) { if(splashDialog.isShowing()){ splashDialog.dismiss(); } break; } canvas = this.surfaceHolder.lockCanvas(null); //通過lockCanvas加鎖並得到該SurfaceView的畫布 Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); if (canvas != null) { canvas.drawPaint(paint); canvas.clipRect(0, 0, ScreenWidth, ScreenHeight); int n = radius; Path mPath = new Path(); mPath.addCircle(cX, cY, n, Path.Direction.CCW); canvas.clipPath(mPath, Region.Op.DIFFERENCE); canvas.drawColor(Color.GRAY); } radius += rate; if (canvas != null) { this.surfaceHolder.unlockCanvasAndPost(canvas); // 釋放鎖並提交畫布進行重繪 } } } else { //第一次運行 canvas = this.surfaceHolder.lockCanvas(null); // 通過lockCanvas加鎖並得到該SurfaceView的畫布 if (canvas != null) { canvas.clipRect(0, 0, ScreenWidth, ScreenHeight); canvas.drawColor(Color.WHITE); canvas.drawBitmap(bmp, 0, 0, null); this.surfaceHolder.unlockCanvasAndPost(canvas); } firstRun = false; } } @Override public void surfaceDestroyed(SurfaceHolder arg0) { Log.i("Test","surfaceDestroyed"); } @Override public void surfaceCreated(SurfaceHolder arg0) { Log.i("Test","surfaceCreated"); doSufaceAnimation(); } public void doSufaceAnimation() { this.thread = new Thread(MySurfaceView.this); this.thread.start(); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // 這裡是SurfaceView發生變化的時候觸發的部分 }
SplashScreen 的建構子需要傳入上下文環境:
public SplashScreen(ReactApplicationContext reactContext,Activity activity) { super(reactContext); this.activity = activity; }
開機顯示畫面時,先初始化各項控制元件:
private void showSplashScreen() { Log.i("Test", "showSplashScreen"); final int drawableId = getSplashId(); getActivity().runOnUiThread(new Runnable() { public void run() { // Get reference to display // rl = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); firstRun = true; Resources resources = activity.getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); handler = new Handler(); ScreenWidth = dm.widthPixels; ScreenHeight = dm.heightPixels; rate = 40; int a = ScreenWidth; int b = ScreenHeight; MaxRaduis = (int) Math.sqrt(a * a + b * b) / 2 + 100; // a*a+b*b開根 getBitmap(drawableId);//處理圖片 surfaceView = new MySurfaceView(activity.getApplicationContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); surfaceView.setLayoutParams(params); surfaceView.getLayoutParams().height=ScreenHeight - getStatusBarHeight(); surfaceView.getLayoutParams().width=ScreenWidth; surfaceView.setClickable(false);//動畫期間不能點擊,線程影響 surfaceView.setZOrderOnTop(true);//最上層surfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);//設置畫布 背景透明 //必須在dialog內添加surfaceView,RN內 //RootView沒法添加SurfaceView splashDialog = new Dialog(activity, android.R.style.Theme_Translucent_NoTitleBar); splashDialog.setContentView(surfaceView); splashDialog.setCancelable(false); splashDialog.show(); } }); }
處理圖片並適配螢幕時要特別注意:為了讓開機時 Application 載入圖片的位置與後續顯示的位置保持一致,這裡必須計算狀態欄的高度:
private void getBitmap(int drawableId) { radius = 12; cX = ScreenWidth / 2; cY = ScreenHeight / 2;//要加上狀態欄高度 bitmap = BitmapFactory.decodeResource(activity.getResources(), drawableId); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int oldwidth = bitmap.getWidth(); int oldheight = bitmap.getHeight(); int newWidth = ScreenWidth; int newHeight = ScreenHeight; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, oldwidth, oldheight, matrix, true); bitmap.recycle();//回收內存 int h = getStatusBarHeight();// 裁切後所取的區域左上角y坐標 ,狀態欄高度 int w = 0;// 裁切後所取的區域左上角x坐標 bmp = Bitmap.createBitmap(resizedBitmap, w, h, resizedBitmap.getWidth(), resizedBitmap.getHeight() - h, null, false); resizedBitmap.recycle();//回收內存 }
取得狀態欄高度的方法:
public int getStatusBarHeight() { int result = 0; int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = activity.getResources().getDimensionPixelSize(resourceId); } return result; }
圖片採用的是 Android 本地資源:
private int getSplashId() { int drawableId = getActivity().getResources().getIdentifier("%圖片文件名稱%", "drawable", getActivity().getClass().getPackage().getName()); if (drawableId == 0) { drawableId = getActivity().getResources().getIdentifier("%圖片文件名稱%", "drawable", getActivity().getPackageName()); } return drawableId; }
最後提供兩個標註 @ReactMethod 的方法給 JS 端呼叫:
@ReactMethod public void showSplash(){ showSplashScreen();//開始遮擋主屏幕 } /** * 提供js點用方法,圓形展開動畫開始 */ @ReactMethod public void doAnimation() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } getActivity().runOnUiThread(new Runnable() { public void run() { if (splashDialog != null && splashDialog.isShowing()) { handler = new Handler(); // rl = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); rl = (ViewGroup) ((ViewGroup) splashDialog.getWindow().getDecorView()).getChildAt(0); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); // 一個自定義的布局,作為顯示的內容 ImageView contentView = new ImageView(activity); contentView.setLayoutParams(params); contentView.setImageBitmap(bmp); popupWindow = new PopupWindow(contentView, ScreenWidth, ScreenHeight - getStatusBarHeight(), true); popupWindow.setTouchable(false); popupWindow.setBackgroundDrawable(null); popupWindow.setAnimationStyle(R.style.PopupAnimation); popupWindow.showAtLocation(rl, Gravity.CENTER_HORIZONTAL, cX, cY); handler.postDelayed(new Runnable() { @Override public void run() { surfaceView.doSufaceAnimation(); } }, 144);//為了讓popwindow有足夠時間顯示圖片 handler.postDelayed(new Runnable() { @Override public void run() { popupWindow.dismiss(); } }, 500);//這裡執行的時間要與popwindow漸變消失的動畫時間一致,popwindow的動畫,就不詳述了,開始動畫也是可以做到漸變消失的,只要最後把popwindow移除久可以了 } } });
SplashScreenPackage 需要實作 ReactPackage 介面:
public class SplashScreenPackage implements ReactPackage { private ReactActivity activity; private SplashScreen mModuleInstance; public SplashScreenPackage(ReactActivity activity) { super(); this.activity=activity; } @Override public List<nativemodule> createNativeModules(ReactApplicationContext reactContext) { mModuleInstance = new SplashScreen(reactContext,activity); return Arrays.<nativemodule>asList( mModuleInstance ); } @Override public List<class<? extends="" javascriptmodule="">> createJSModules() { return Collections.emptyList(); } @Override public List<viewmanager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<viewmanager>asList(); } }
為了把上下文環境傳進 SplashScreen,MainApplication 與 MainActivity 也需要小幅調整。首先在 MainApplication 中拿掉 finally,並補上一個 setter 方法:
//mainApplication中去掉了finally private ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<reactpackage> getPackages() { return Arrays.<reactpackage>asList( new MainReactPackage() ); } }; //添加set方法 public void setmReactNativeHost(ReactNativeHost mReactNativeHost) { this.mReactNativeHost = mReactNativeHost; }
MainActivity 則需要重寫 ReactRootView,因為這個方法執行後就會依據 Application 的 ReactPackage 來建構控制元件:
@Override
protected ReactRootView createRootView() {
ma=(MainApplication)this.getApplication();
ma.setmReactNativeHost( new ReactNativeHost(ma) {
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override protected List<reactpackage> getPackages() { return Arrays.<reactpackage>asList( new MainReactPackage(), new SplashScreenPackage(MainActivity.this) ); } }); return super.createRootView(); }
最後還有一個實作上的小細節:當 PopupWindow 彈出時,畫面可能會出現閃屏,建議在 PopupWindow 裡改用透明背景的圖片來顯示,這樣閃屏的突兀感會明顯降低。
這就是最終完成的成果,不過模擬器跑起來有點卡,實際效果會更順):

Android 屬性動畫深入:ValueAnimator 與 ObjectAnimator 用法全解
屬性動畫是 API 11 引入的新特性。與 View 動畫相比,它最大的突破在於擴展了作用對象——屬性動畫可以對任意對象做動畫,也不像 View 動畫那樣只支持四種簡單變
高德地圖定位失敗怎麼辦?分平台排查重點整理
高德地圖提供全國地圖瀏覽、地點搜尋與路線規劃,還能順便看商家的團購優惠。但一旦定位失敗,這些功能幾乎都跟著失效。以下依平台整理排查重點。 iPhone 使用者 到「
微信網頁第三方登錄原理詳解:OAuth2.0 全流程拆解
微信開放平台與公眾平台的區別1. 公眾平台面向普通用戶,如自媒體、媒體與企業官方帳號的運營人員。若團隊有開發能力,也能調用自定義菜單、自動回覆、查詢等接口,目前多數通過認
Android 網路編程(四):從原始碼解析 Volley
Volley 是 Android 上常用的網路請求框架。它將請求加入佇列,由快取與網路調度線程處理,最後把結果回傳主線程。整體架構Volley 主要包含主線程、快取調度線