2016-05-16 53 views
0

我绘制了一个画布位图并试图计算无色区域的百分比。 我发现了一些方法,但他们没有计算像素,当我完成绘制屏幕并且我已经离开了一个很小的未知区域时,该方法写下了我完成的。android canvas以百分比计算区域彩色像素

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

我不确定你为什么要做所有这些预缩放,但是常规数学首先计算出你需要的数字,然后将其缩放到你想要的结果。预缩放可能会很容易导致错误。事情是这样的:

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你会达到几次处理速度更快花费太长时间才能完成(甚至你也可以是相当更复杂的实现)。

+0

谢谢,但它花了很多时间 –

+0

我认为它会的,但它是如何工作的,如果你想要一个可靠的数学,你需要扫描所有的像素,并扫描所有的像素需要时间。但这就是为什么我在最后添加了观察结果,并提到使用RenderScript可以使其更快 – Budius