如何在画布上获取绘图元素大小?

时间:2014-09-01 07:38:49

标签: android android-layout canvas view

enter image description here

我正在制作一个“带面具的绘画”应用程序。当用户在屏幕上拖动时,它会清除部分遮罩。

我通过cavans和setXfermode Clear

实现了它
// Specify that painting will be with fat strokes:
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(canvas.getWidth() / 15);

// Specify that painting will clear the pixels instead of paining new ones:
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

cv.drawPath(path, drawPaint);

问题是,如何才能获得清理空间的百分比?,没有必要准确,只需粗略地检测超过一半的屏幕尺寸是否干净。感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您需要做的是将canvas转换为位图,并计算其中black pixels的数量。使用简单的数学运算,您可以将黑色像素的数量除以画布中的像素数,这将为您提供黑色像素的百分比。

示例taken from this post

 public float percentTransparent(Bitmap bm) { //pass the converted bitmap of canvas
    final int width = bm.getWidth();
    final int height = bm.getHeight();

    int totalBlackPixels = 0;
    for(int x = 0; x < width; x++) {
        for(int y = 0; y < height; y++) {
            if (bm.getPixel(x, y) == Color.BLACK) {
                totalBlackPixels ++;
            }
        }
    }
    return ((float)totalBlackPixels )/(width * height); //returns the percentage of black pixel on screen

}