在我的应用程序中,如果图像未填充imageView,我将截屏,然后将透明像素添加到位图中。是否可以从位图中删除透明像素或截取没有透明像素的屏幕截图。

最佳答案

此方法快很多:

static Bitmap trim(Bitmap source) {
    int firstX = 0, firstY = 0;
    int lastX = source.getWidth();
    int lastY = source.getHeight();
    int[] pixels = new int[source.getWidth() * source.getHeight()];
    source.getPixels(pixels, 0, source.getWidth(), 0, 0, source.getWidth(), source.getHeight());
    loop:
    for (int x = 0; x < source.getWidth(); x++) {
        for (int y = 0; y < source.getHeight(); y++) {
            if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
                firstX = x;
                break loop;
            }
        }
    }
    loop:
    for (int y = 0; y < source.getHeight(); y++) {
        for (int x = firstX; x < source.getWidth(); x++) {
            if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
                firstY = y;
                break loop;
            }
        }
    }
    loop:
    for (int x = source.getWidth() - 1; x >= firstX; x--) {
        for (int y = source.getHeight() - 1; y >= firstY; y--) {
            if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
                lastX = x;
                break loop;
            }
        }
    }
    loop:
    for (int y = source.getHeight() - 1; y >= firstY; y--) {
        for (int x = source.getWidth() - 1; x >= firstX; x--) {
            if (pixels[x + (y * source.getWidth())] != Color.TRANSPARENT) {
                lastY = y;
                break loop;
            }
        }
    }
    return Bitmap.createBitmap(source, firstX, firstY, lastX - firstX, lastY - firstY);
}

09-13 05:33