android canvas以百分比计算区域彩色像素

时间:2016-05-16 08:34:19

标签: android canvas percentage pixels

我绘制一个画布位图并尝试以百分比计算未着色区域。 我找到了一些方法,但他们没有计算像素,当我完成绘制屏幕并且我留下了一个小的揭开区域时,方法写了我完成。

 public float percentTransparent(Bitmap bm, int scale) {

    final int width = bm.getWidth();
    final int height = bm.getHeight();

    // size of sample rectangles
    final int xStep = width/scale;
    final int yStep = height/scale;

    // center of the first rectangle
    final int xInit = xStep/2;
    final int yInit = yStep/2;

    // center of the last rectangle
    final int xEnd = width - xStep/2;
    final int yEnd = height - yStep/2;

    int totalTransparent = 0;

    for(int x = xInit; x <= xEnd; x += xStep) {
        for(int y = yInit; y <= yEnd; y += yStep) {
            if (bm.getPixel(x, y) == Color.TRANSPARENT) {
                totalTransparent++;
            }
        }
    }
    return ((float)totalTransparent) / (scale * scale);

}

这是我找到的方法。

1 个答案:

答案 0 :(得分:1)

我不确定你为什么要进行所有那些预缩放,但是传统的数学算法首先计算你需要的数字,然后你将它缩放到你想要的结果。预缩放可能很容易导致错误。像这样:

 public float percentTransparent(Bitmap bm, float scale) {

    int width = bm.getWidth();
    int height = bm.getHeight();
    int area = width * height;
    int totalTransparent = 0;

    for(int x = 0; x <= width; x ++) {
        for(int y = 0; y <= height; y ++) {
            if (bm.getPixel(x, y) == Color.TRANSPARENT) {
                totalTransparent++;
            }
        }
    }

    // so here we know for sure that `area` is the total pixels
    // and `totalTransparent` are the total pixels not colored
    // so to calculate percentage is a simple percentage

   float percTransparent = 
        ((float)totalTransparent) / 
        ((float)area)

   // at the end you can scale your final result
  ... return something with `percTransparent` and `scale`

}

ps。:如果使用RenderScript完成此处理的时间太长(即使实现起来要复杂得多),您也可以快几倍地完成处理。