はじめに
AndroidアプリでBitmapにブラー処理を行う実装方法を紹介。
例えばメニューやダイアログを開いたりする時に、表示している画面の上に磨りガラスのような
効果をつけてダイアログを表示したいというようなことがあるとする時に使える。(Etsyアプリとか)
今回はRenderScriptを使って、iOSのガラス処理みたいなことを実装。
実装方法
Gradle
Gradle側でRenderScriptを使用するための記述をする
android {
defaultConfig {
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
}
Activity
RenderScriptとImageViewを用意
Activity
private RenderScript rs; // RenderScript
private ImageView image; // 画像をセットするImageView
それぞれを初期化して、画像をブラーする
Activity
try{
rs = RenderScript.create(this);
image = (ImageView)findViewById(R.id.picture);
// 第二引数は加工する元のBitmap
blurProcess(image, bmp);
}catch (Exception e){
//nop
}
Activity
private void blurProcess(final ImageView img, final Bitmap bmp) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Allocation alloc = Allocation.createFromBitmap(rs, bmp);
ScriptIntrinsicBlur blur =
ScriptIntrinsicBlur.create(rs, alloc.getElement());
blur.setRadius(15f); // ブラーする度合い
blur.setInput(alloc);
blur.forEach(alloc);
alloc.copyTo(bmp); // 加工した画像をbmpに移す
} catch (Exception e) {
// nop
}
return null;
}
@Override
protected void onPostExecute(Void v) {
// 画像をセット
img.setImageBitmap(bmp);
}
}.execute(null, null, null);
}
これだけでOK!
これでImageViewにはブラー加工された画像がセットされる