RenderScript使用教程(一)

4 篇文章 0 订阅

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。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值