为Renderscript中的位图计算透明像素的计数器

时间:2019-01-01 13:30:13

标签: java android android-renderscript

我的问题是要获取由于用户的OnTouchEvent而更改的图像中透明部分/像素的数量。

所以我想将以下Java代码转换为renderscript代码:

public int transparentPixels(){  

    int amount = 0;

    for(int x = 0; x < sourceBitmap.getWidth(); x++){
        for(int y = 0; y < sourceBitmap.getHeight(); y++){

            if(sourceBitmap.getPixel(x,y) == Color.TRANSPARENT){

                amount += 1;

            }

        }
    }

    return amount;
}

请从rs和java文件中添加代码段。

谢谢!

1 个答案:

答案 0 :(得分:0)

参考:RenderScript DocsrsAtomicInc

这是我的示例代码。请参阅winklerrr的解决方案here

RSexample.rs

使用in-> a检索alpha并检查其值。

#pragma version(1)
#pragma rs java_package_name(RS)
#pragma rs_fp_relaxed

int32_t count = 0;
rs_allocation rsAllocationCount;

void countPixels(uchar4* in, uint x, uint y) {
  if(in->a==0)rsAtomicInc(&count);
  rsSetElementAt_int(rsAllocationCount, count, 0);
}

RSContext.java

充当MainActivity.java和RSexample.rs之间的上下文。

public void init(Context context) {
    rs = RenderScript.create(context);
    scriptC_RS = new ScriptC_RSexample(rs);
}
public void setup(int w, int h){
    rgb888Type = Type.createXY(rs, Element.RGBA_8888(rs), w, h);
    allocIn = Allocation.createTyped(rs, rgb888Type, Allocation.USAGE_SCRIPT);
    allocCount = Allocation.createTyped(rs, Type.createX(rs, Element.I32(rs), 1));
}
public void addPic(Bitmap bitmap) {
    allocIn = Allocation.createFromBitmap(rs, bitmap);
}
public int getCount(){
    scriptC_RS.set_rsAllocationCount(allocCount);
    scriptC_RS.forEach_countPixels(allocIn);
    int[] count = new int[1];
    allocIn.syncAll(Allocation.USAGE_SCRIPT);
    allocCount.copyTo(count);
    return count[0];
}

MainActivity.java

RSContext rsContext = new RSContext();
rsContext.init(this);
rsContext.setup(bitmap.getWidth(), bitmap.getHeight());
rsContext.addPic(bitmap);
int transparentPixel = rsContext.getCount();