首页  编辑  

android中使用renderscript的最简单方法

Tags: /Android/   Date Created:
在安卓Studio当中,使用RenderScript(rs文件)的简单方法:
1. 修改App的build.gradle,在
android {
	defaultConfig {
		# 增加renderscript支持
		renderscriptTargetApi 18
		renderscriptSupportModeEnabled true
   	}
}
2. 在src\main目录下,新建 rs 目录,然后在下面放好对应的rs文件,例如 yuv2rgb.rs
#pragma version(1)
#pragma rs java_package_name(zhjinrui.camera)
#pragma rs_fp_relaxed

rs_allocation gYUV;
uint32_t gW;
uint32_t gH;

uchar4 __attribute__((kernel)) YUV2RGB(uint32_t x,uint32_t y)
{
    uchar yps = rsGetElementAt_uchar(gYUV, x, y);
    uchar u = rsGetElementAt_uchar(gYUV,(x & ~1),gH + (y>>1));
    uchar v = rsGetElementAt_uchar(gYUV,(x & ~1)+1,gH + (y>>1));
    uchar4 rgb = rsYuvToRGBA_uchar4(yps, u, v);
    return rgb;
}
3. 在java代码中,import相关的package
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicYuvToRGB;
import android.support.v8.renderscript.Type;
4. 使用代码:
renderScript = RenderScript.create(context);
public Bitmap Yuv2Bitmap(byte[] yuv,int W,int H) {
    Type.Builder yuvBlder = new Type.Builder(renderScript, Element.U8(renderScript)).setX(W).setY(H*3/2);
    Allocation allocIn = Allocation.createTyped(renderScript,yuvBlder.create(),Allocation.USAGE_SCRIPT);
    Type rgbType = Type.createXY(renderScript, Element.RGBA_8888(renderScript), W, H);
    Allocation allocOut = Allocation.createTyped(renderScript,rgbType,Allocation.USAGE_SCRIPT);

    ScriptC_yuv2rgb scriptC_yuv2rgb  = new ScriptC_yuv2rgb(renderScript);
    allocIn.copyFrom(yuv);
    scriptC_yuv2rgb.set_gW(W);
    scriptC_yuv2rgb.set_gH(H);
    scriptC_yuv2rgb.set_gYUV(allocIn);
    scriptC_yuv2rgb.forEach_YUV2RGB(allocOut);

    Bitmap bmp = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888);
    allocOut.copyTo(bmp);

    allocIn.destroy();
    scriptC_yuv2rgb.destroy();
    return bmp;
}