編輯:關於 Android 程式設計
前言
Yahoo 天氣的畫面上滑時,背景圖會跟著移動,而且模糊程度會隨手指位移而變化。看起來相當吸引人,但心裡也會打個問號:在 Android 上做模糊渲染很吃 CPU 也很耗時,處理不好就是一路掉幀。
一般來說,論效能排序:OpenGL 最佳,C/C++ 次之,純 Java 最慢。不過自從 Android 推出 RenderScript 之後多了一個選項——實測它的渲染效率與 C/C++ 相當,卻比走 JNI 簡單得多,而且官方提供了支援庫,低版本也能用。
實務上有個前提:尽量不要拿原始解析度的圖去模糊,先按比例縮小,渲染效率會好很多。
用 RenderScript 模糊一張圖
核心程式碼如下:
public class BlurBitmap { /** 圖片縮放比例 */ private static final float BITMAP_SCALE = 0.4f; /** 最大模糊度(0.0 到 25.0 之間) */ private static final float BLUR_RADIUS = 25f; public static Bitmap blur(Context context, Bitmap image) { int width = Math.round(image.getWidth() * BITMAP_SCALE); int height = Math.round(image.getHeight() * BITMAP_SCALE); // 縮圖後作為渲染輸入 Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false); Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap); RenderScript rs = RenderScript.create(context); ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // RenderScript 不走 VM 記憶體配置,必須用 Allocation // 建立時記憶體是空的,需以 copyTo() 把資料填進去 Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap); Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap); blurScript.setRadius(BLUR_RADIUS); // 25f 是最大模糊度 blurScript.setInput(tmpIn); blurScript.forEach(tmpOut); tmpOut.copyTo(outputBitmap); return outputBitmap; } }
另外要在 app 的 gradle 中開啟支援模式:
defaultConfig { ...... renderscriptTargetApi 19 renderscriptSupportModeEnabled true }
模糊前後的效果對比:

動態模糊怎麼做
即使換用了 RenderScript,實測一張 500×700 的 PNG 在我的裝置上仍要花約 50ms。也就是說,想靠它即時運算每幀的模糊程度,畫面一定會卡。
於是要換個思路:先把圖片預先模糊到最大強度,再把原圖疊在上面,透過改變原圖的 alpha 值來模擬不同程度的模糊。
public class MainActivity extends AppCompatActivity { /** 原始圖片控件 */ private ImageView mOriginImg; /** 模糊後的圖片控件 */ private ImageView mBluredImage; /** 進度條SeekBar */ private SeekBar mSeekBar; /** 顯示進度的文字 */ private TextView mProgressTv; /** 透明度 */ private int mAlpha; /** 原始圖片 */ private Bitmap mTempBitmap; /** 模糊後的圖片 */ private Bitmap mFinalBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); mTempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dayu); mFinalBitmap = BlurBitmap.blur(this, mTempBitmap); mBluredImage.setImageBitmap(mFinalBitmap); mOriginImg.setImageBitmap(mTempBitmap); setSeekBar(); } private void initViews() { mBluredImage = (ImageView) findViewById(R.id.activity_main_blured_img); mOriginImg = (ImageView) findViewById(R.id.activity_main_origin_img); mSeekBar = (SeekBar) findViewById(R.id.activity_main_seekbar); mProgressTv = (TextView) findViewById(R.id.activity_main_progress_tv); } private void setSeekBar() { mSeekBar.setMax(100); mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mAlpha = progress; mOriginImg.setAlpha((int) (255 - mAlpha * 2.55)); mProgressTv.setText(String.valueOf(mAlpha)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
布局檔:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:layout_width="match_parent" android:layout_weight="1" android:layout_height="0dp"> <ImageView android:id="@+id/activity_main_blured_img" android:scaleType="centerCrop" android:src="@drawable/dayu" android:layout_width="match_parent" android:layout_height="match_parent"/> <ImageView android:id="@+id/activity_main_origin_img" android:scaleType="centerCrop" android:layout_width="match_parent" android:layout_height="match_parent"/> </FrameLayout> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="80dp"> <SeekBar android:layout_marginTop="@dimen/activity_vertical_margin" android:id="@+id/activity_main_seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"/> <TextView android:id="@+id/activity_main_progress_tv" android:text="0" android:textSize="24sp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> </LinearLayout>
效果:

關鍵就兩步:呼叫一次模糊方法,然後在 SeekBar 的監聽裡改原圖的 setAlpha()。
進一步:仿 Yahoo 天氣的首頁
有了這層基礎,要模仿 Yahoo 天氣的首頁就只是再加兩件事:
1、監聽滑動手勢,呼叫 setTop() 把背景圖往上平移
2、平移的同時必須手動把圖片高度加一截,否則底部會露出留白
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int height = point.y; ViewGroup.LayoutParams params = imageView.getLayoutParams(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; // 高度多加 100,避免上移後底部露白 params.height = height + 100; imageView.requestLayout();
兩點做完,首頁的視覺基本就到位了。
加上滑動聯動後的最終效果:

總結
整篇的核心思路是「預算一次、之後只調 alpha」:RenderScript 負責把昂貴的模糊運算做完一次,執行期只留最便宜的透明度變化,藉此換到流暢度。有興趣動手做一遍,會對 Android 的繪製成本更有概念。
Android 事件傳遞機制透視:從 dispatchTouchEvent 到 onInterceptTouchEvent
自定義控件時,「點擊沒反應」「滑動被父容器搶走」這類問題幾乎繞不開事件傳遞。本文結合一個可運行的 Demo 與系統源碼,把 ACTION_DOWN 到 ACTION_UP
手機QQ怎麼省流量 一個開關屏蔽群聊圖片
是不是總覺得流量不夠用?仔細回想才發現,流量都耗在手機QQ的群聊裡了。現在手上的QQ群越來越多,群友又愛發圖片與視頻,那該怎麼省下這部分消耗?下面就一起來看。 手機QQ省
淺談 Android 官方 MVP 架構:從 MVC 的困境到三層職責分離
一、為什麼要從 MVC 換到 MVP Android 應用本身可以視為一套 MVC:XML 佈局充當 View,Activity 充當 Controller。但實踐中 A
Android 自定義 Dialog 使用方法
Dialog 是 Android 中常見的互動元件,用於提示、確認、表單輸入或列表選擇。除了系統預設樣式,開發者也可以自定義布局,讓對話框更符合產品視覺。 自定義 Dia