簡單記錄:
RenderScript主要在android中的對圖形進行處理是己,RenderScript采用C99語法進行編寫,主要優(yōu)勢在于性能較高悲龟,本次記錄主要是利用RenderScript對圖片進行模糊化邓萨。
- 需要注意的地方:
如果只需要支持19以上的設(shè)備朋沮,只需要使用android.renderscript包下的相關(guān)類即可,而如果需要向下兼容囱淋,則需要使用android.support.v8.renderscript包下的相關(guān)類猪杭,兩個包的類的操作都是一樣的。
- 使用RenderScript的時候需要在build.gradle中添加如下代碼:
defaultConfig {
..................
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
- 使用android.support.v8.renderscript包時的坑:
當使用此包時妥衣,需要注意皂吮,經(jīng)測試,當buildToolsVersion為23.0.3時税手,在4.4以上的部分設(shè)備會崩潰蜂筹,原因是因為沒有導(dǎo)入libRSSupport.so包。當buildToolsVersion為23.0.1時芦倒,在4.4以上的部分設(shè)備會崩潰艺挪,原因是沒有renderscript-v8.jar包,這兩個地方暫時沒有解決的辦法兵扬,所以在使用android.support.v8.renderscript包的時候麻裳,不要用23.0.3或者23.0.1進行構(gòu)建,以免出錯器钟。
- 下面是一個小例子工具類:
package com.chenh.RenderScript;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
public class BlurBitmap {
//圖片縮放比例
private static final float BITMAP_SCAL = 0.4f;
//最大模糊度(在0.0到25.0之間)
private static final float BLUR_RADIUS = 25f;
/**
* 模糊圖片的具體操作方法
*
* @param context 上下文對象
* @param image 需要模糊的圖片
* @return 模糊處理后的圖片
*/
public static Bitmap blur(Context context, Bitmap image) {
//計算圖片縮小后的長寬
int width = Math.round(image.getWidth() * BITMAP_SCAL);
int height = Math.round(image.getHeight() * BITMAP_SCAL);
//將縮小后的圖片做為預(yù)渲染的圖片
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
//創(chuàng)建一張渲染后的輸出圖片
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
//創(chuàng)建RenderScript內(nèi)核對象
RenderScript rs = RenderScript.create(context);
//創(chuàng)建一個模糊效果的RenderScript的工具對象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//由于RenderScript并沒有使用VM來分配內(nèi)存津坑,所以需要使用Allocation類來創(chuàng)建和分配內(nèi)存空間
//創(chuàng)建Allocation對象的時候其實內(nèi)存是空的,需要使用copyTo()將數(shù)據(jù)填充進去傲霸。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
//設(shè)置渲染的模糊程度疆瑰,25f是最大模糊程度
blurScript.setRadius(BLUR_RADIUS);
//設(shè)置blurScript對象的輸入內(nèi)存
blurScript.setInput(tmpIn);
//將輸出數(shù)據(jù)保存到輸出內(nèi)存中
blurScript.forEach(tmpOut);
//將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}