【问题标题】:How to get the draw element size on a cavans?如何在画布上获取绘图元素大小?
【发布时间】:2014-09-01 07:38:49
【问题描述】:

我正在开发一个“使用蒙版绘图”应用程序。当用户在屏幕上拖动时,它会清除部分遮罩。

我通过 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);

问题是,怎样才能得到清理空间的百分比?不需要很准确,粗略检测一下屏幕大小的一半以上什么时候清理了。感谢帮助

【问题讨论】:

    标签: android android-layout canvas view


    【解决方案1】:

    你需要做的就是将你的canvas转换成位图,并计算其中black pixels的数量。使用简单的数学运算,您可以将黑色像素的数量除以 canvas 中的像素数量,从而得出黑色像素的百分比。

    样本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
    
    }
    

    【讨论】:

    • 真的令人印象深刻。这工作很棒。最后一个问题,是否可以进行估计而不是 1 像素乘 1 像素?就我而言,它不需要准确
    • @user782104 如果对这篇文章有帮助,请点赞,谢谢,我想不出有一篇来自名为Monte Carlo method 的帖子,它的速度很快,而不是逐个像素地计数
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多