簡(jiǎn)單記錄:
RenderScript主要在android中的對(duì)圖形進(jìn)行處理,RenderScript采用C99語(yǔ)法進(jìn)行編寫(xiě),主要優(yōu)勢(shì)在于性能較高,本次記錄主要是利用RenderScript對(duì)圖片進(jìn)行模糊化。
- 需要注意的地方:
如果只需要支持19以上的設(shè)備,只需要使用android.renderscript包下的相關(guān)類即可,而如果需要向下兼容,則需要使用android.support.v8.renderscript包下的相關(guān)類,兩個(gè)包的類的操作都是一樣的。
- 使用RenderScript的時(shí)候需要在build.gradle中添加如下代碼:
defaultConfig {
..................
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
- 使用android.support.v8.renderscript包時(shí)的坑:
當(dāng)使用此包時(shí),需要注意,經(jīng)測(cè)試,當(dāng)buildToolsVersion為23.0.3時(shí),在4.4以上的部分設(shè)備會(huì)崩潰,原因是因?yàn)闆](méi)有導(dǎo)入libRSSupport.so包。當(dāng)buildToolsVersion為23.0.1時(shí),在4.4以上的部分設(shè)備會(huì)崩潰,原因是沒(méi)有renderscript-v8.jar包,這兩個(gè)地方暫時(shí)沒(méi)有解決的辦法,所以在使用android.support.v8.renderscript包的時(shí)候,不要用23.0.3或者23.0.1進(jìn)行構(gòu)建,以免出錯(cuò)。
- 下面是一個(gè)小例子工具類:
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 上下文對(duì)象
* @param image 需要模糊的圖片
* @return 模糊處理后的圖片
*/
public static Bitmap blur(Context context, Bitmap image) {
//計(jì)算圖片縮小后的長(zhǎng)寬
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)核對(duì)象
RenderScript rs = RenderScript.create(context);
//創(chuàng)建一個(gè)模糊效果的RenderScript的工具對(duì)象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//由于RenderScript并沒(méi)有使用VM來(lái)分配內(nèi)存,所以需要使用Allocation類來(lái)創(chuàng)建和分配內(nèi)存空間
//創(chuàng)建Allocation對(duì)象的時(shí)候其實(shí)內(nèi)存是空的,需要使用copyTo()將數(shù)據(jù)填充進(jìn)去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
//設(shè)置渲染的模糊程度,25f是最大模糊程度
blurScript.setRadius(BLUR_RADIUS);
//設(shè)置blurScript對(duì)象的輸入內(nèi)存
blurScript.setInput(tmpIn);
//將輸出數(shù)據(jù)保存到輸出內(nèi)存中
blurScript.forEach(tmpOut);
//將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}