RenderScript使用教程(一)
Java中使用RenderScript
创建rs目录
编写一个rs脚本文件
// Needed directive for RS to work
#pragma version(1)
// Change java_package_name directive to match your Activity's package path
#pragma rs java_package_name(demo.rs.dong.cn.java_rs_demo)
// Creates a custom structure
typedef struct MyElement {
int x;
int y;
bool simpleBool;
} MyElement_t;
// This kernel function will just sum 2 to every input element
// * in -> Current Allocation element
// * x -> Current element index
int __attribute__((kernel)) sum2(int in, uint32_t x) {
// Performs the sum and returns the new value
return in + 100;
}
修改gradle文件配置
Java调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
javaCallRs();
}
private void javaCallRs() {
long startTime = System.currentTimeMillis();
// Instantiates the RenderScript context.
RenderScript mRS = RenderScript.create(this);
// Create an input array, containing some numbers.
int inputArray[] = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// Instantiates the input Allocation, that will contain our sample
// numbers.
Allocation inputAllocation = Allocation.createSized(mRS, Element.I32(mRS), inputArray.length);
// Copies the input array into the input Allocation.
inputAllocation.copyFrom(inputArray);
// Instantiates the output Allocation, that will contain the result of the process.
Allocation outputAllocation = Allocation.createSized(mRS, Element.I32(mRS), inputArray.length);
// Instantiates the sum script.
ScriptC_sum myScript = new ScriptC_sum(mRS);
// Run the sum process, taking the elements belonging to the inputAllocation and placing
// the process results inside the outputAllocation.
myScript.forEach_sum2(inputAllocation, outputAllocation);
// Copies the result of the process from the outputAllocation to a simple int array.
int outputArray[] = new int[inputArray.length];
outputAllocation.copyTo(outputArray);
Log.d("tag", "time = "+ (System.currentTimeMillis() - startTime));
String debugString = "Output: ";
for (int i = 0; i < outputArray.length; i++)
debugString += String.valueOf(outputArray[i]) + (i < outputArray.length - 1 ? ", " : "");
Toast.makeText(this,debugString,Toast.LENGTH_LONG).show();
}
最后编译运行。这是最简单的一个RenderScript示例,下一节介绍如何通过NDK去调用RenderScript。