編輯:關於 Android 程式設計
翻 RenderScript 官方文件的時候,發現這套 API 相當強悍。其中 ScriptIntrinsic 這個抽象類別底下藏了幾個很實用的子類別,而 ScriptIntrinsicBlur 就是其中之一,專門用來對圖片做高斯模糊。
ScriptIntrinsic 的宣告:

ScriptIntrinsicBlur 類別的宣告:

對照 SDK 內附的範例專案讀了一遍之後,我自己也寫了一個高斯模糊。(範例位置:SDK目錄/samples/android-19/renderscript/RenderScriptIntrinsic/RenderScriptIntrinsicSample/)
效果如下:

支援包的路徑是 sdk目錄/buildtools/任意版本號/renderscript/lib/renderscript-v8.jar。
另外,為了避開部分機型的相容問題,建議把 renderscript-v8.jar 同目錄下 packaged 資料夾中的所有函式庫也一并複製到 lib 底下。

private SeekBar blurSeekBar;//拖動條 private ImageView img_blur;//顯示模糊後bitmap的ImageView //原bitmap和高斯模糊後的bitmap private Bitmap bitmap_original, bitmap_blur; //高斯模糊處理的AsyncTask private RenderScriptTask mLatestTask = null; //RenderScript 對象(Google的高性能並行計算類,他可以利用設備的GPU/CPU等計算資源) private RenderScript mRS; //下面是兩個RenderScript的傳入參數對象 private Allocation mInAllocation; private Allocation mOutAllocation; //高斯模糊處理實例 private ScriptIntrinsicBlur mScriptBlur;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); blurSeekBar = (SeekBar) findViewById(R.id.aty_main_seekBar); img_blur = (ImageView) findViewById(R.id.aty_main_img_blur); bitmap_original = loadBitmap(R.drawable.meet_entry_guide_3); // 復制一份 bitmap_blur = Bitmap.createBitmap(bitmap_original.getWidth(), bitmap_original.getHeight(), bitmap_original.getConfig()); createBlureScript(); setSeekBarListening();//為SeekBar設置拖拽監聽 } /** * Helper to load Bitmap from resource */ private Bitmap loadBitmap(int resource) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeResource(getResources(), resource, options); } /** * 創建Script */ private void createBlureScript() { mRS = RenderScript.create(this); mInAllocation = Allocation.createFromBitmap(mRS, bitmap_original); mOutAllocation = Allocation.createFromBitmap(mRS, bitmap_blur); /* * Create intrinsics. RenderScript has built-in features such as blur, * convolve filter etc. These intrinsics are handy for specific * operations without writing RenderScript kernel. In the sample, it's * creating blur, convolve and matrix intrinsics. */ mScriptBlur = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS)); }
private void performFilter(Allocation inAllocation, Allocation outAllocation, Bitmap bitmapOut, float value) { /* * 設置模糊程度。范圍在0~25之間。否則會出錯 */ mScriptBlur.setRadius(value); /* * Invoke filter kernel */ mScriptBlur.setInput(inAllocation); mScriptBlur.forEach(outAllocation); outAllocation.copyTo(bitmapOut); }
// Request UI update img_blur.setImageBitmap(bitmap_blur); img_blur.invalidate();
步驟一:建立並初始化物件(只需一次)
mRS = RenderScript.create(this); mScriptBlur = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS)); //RenderScript的輸入和輸出參數對象 mInAllocation = Allocation.createFromBitmap(mRS, bitmap_original); mOutAllocation = Allocation.createFromBitmap(mRS, bitmap_blur);
步驟二:執行模糊並把結果複製出來
/* * 設置模糊程度。范圍在0~25之間。否則會出錯(這個也可以只設置一次) */ mScriptBlur.setRadius(value); /* * Invoke filter kernel */ mScriptBlur.setInput(inAllocation); mScriptBlur.forEach(outAllocation); //將結果拷貝出來,拷貝到bitmapOut對象中 outAllocation.copyTo(bitmapOut);
步驟三:回收 RenderScript 物件
mRS.destory(); mRs = null;
這裡要特別提醒 setRadius() 的範圍必須落在 0 到 25 之間,超出範圍會直接出錯。另外別忘了最後的資源回收,RenderScript 物件若不釋放,在多次進入頁面的情況下很容易造成記憶體問題。
public class MainActivity extends Activity { private SeekBar blurSeekBar; private ImageView img_blur; private Bitmap bitmap_original, bitmap_blur; private RenderScriptTask mLatestTask = null; private RenderScript mRS; private Allocation mInAllocation; private Allocation mOutAllocation; private ScriptIntrinsicBlur mScriptBlur; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); blurSeekBar = (SeekBar) findViewById(R.id.aty_main_seekBar); img_blur = (ImageView) findViewById(R.id.aty_main_img_blur); bitmap_original = loadBitmap(R.drawable.meet_entry_guide_3); // 復制一份 bitmap_blur = Bitmap.createBitmap(bitmap_original.getWidth(), bitmap_original.getHeight(), bitmap_original.getConfig()); createBlureScript(); setSeekBarListening(); } /** * 設置SeekBar的監聽 */ private void setSeekBarListening() { blurSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateImage(progress); } }); } /** * 創建Script */ private void createBlureScript() { mRS = RenderScript.create(this); mInAllocation = Allocation.createFromBitmap(mRS, bitmap_original); mOutAllocation = Allocation.createFromBitmap(mRS, bitmap_blur); /* * Create intrinsics. RenderScript has built-in features such as blur, * convolve filter etc. These intrinsics are handy for specific * operations without writing RenderScript kernel. In the sample, it's * creating blur, convolve and matrix intrinsics. */ mScriptBlur = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS)); } private void performFilter(Allocation inAllocation, Allocation outAllocation, Bitmap bitmapOut, float value) { /* * Set blur kernel size */ mScriptBlur.setRadius(value); /* * Invoke filter kernel */ mScriptBlur.setInput(inAllocation); mScriptBlur.forEach(outAllocation); outAllocation.copyTo(bitmapOut); } /* * In the AsyncTask, it invokes RenderScript intrinsics to do a filtering. * After the filtering is done, an operation blocks at Allication.copyTo() * in AsyncTask thread. Once all operation is finished at onPostExecute() in * UI thread, it can invalidate and update ImageView UI. */ private class RenderScriptTask extends AsyncTask<Float, Integer, Integer> { Boolean issued = false; protected Integer doInBackground(Float... values) { if (isCancelled() == false) { issued = true; performFilter(mInAllocation, mOutAllocation, bitmap_blur, values[0]); } return 0; } void updateView(Integer result) { // Request UI update img_blur.setImageBitmap(bitmap_blur); img_blur.invalidate(); } protected void onPostExecute(Integer result) { updateView(result); } protected void onCancelled(Integer result) { if (issued) { updateView(result); } } } /* * Invoke AsynchTask and cancel previous task. When AsyncTasks are piled up * (typically in slow device with heavy kernel), Only the latest (and * already started) task invokes RenderScript operation. */ private void updateImage(int progress) { float f = getBlureParam(progress); if (mLatestTask != null) mLatestTask.cancel(false); mLatestTask = new RenderScriptTask(); mLatestTask.execute(f); } /** * 模糊的值在1 ~ 25之間 * * @param progress * SeekBar的進度值(0 ~ 100) * @return 模糊值 */ private float getBlureParam(int progress) { final float max = 25.0f; final float min = 1.f; return (float) ((max - min) * (progress / 100.0) + min); } /** * Helper to load Bitmap from resource */ private Bitmap loadBitmap(int resource) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeResource(getResources(), resource, options); } }
值得注意的是,範例中把模糊運算包在 AsyncTask 裡,並在每次更新前取消前一個 Task。這是因為拖动條滑動時會連續觸發多次運算,若不取消舊任務,在效能較差的裝置上會堆積成一串,畫面就會卡住。
Android 垂直跑馬燈升級:加入圖片內容
原本只支援文字舊版垂直跑馬燈多半只針對 TextView 設計,若需求變成圖文並用,就需要調整原本元件。可將項目視圖改為包含 ImageView 與 TextView 的
Android IPC 機制(一):IPC 概念與 Binder 運作原理
IPC 是什麼 IPC 是 Inter-Process Communication 的縮寫,指進程間通訊。在 Android 中,不同進程可能擁有自己的虛擬機與記憶體空間
用 WebView 實作一個簡易瀏覽器:返回、前進、首頁、網址輸入
WebView 是 Android 內建的網頁檢視元件,包一層操作列就能做出一個雛形瀏覽器。本篇實作的功能包含:網址輸入與跳轉、返回上一頁、前進下一頁、回到首頁、退出,
Android自定義安全輸入法:防止密碼被第三方竊取
本文為大家分享一個自定義輸入法的實現示例,供感興趣的讀者參考。 對於Android用戶來說,大多數人都習慣使用第三方輸入法。然而在輸入密碼(尤其是支付相關的密碼)時,第三