android - 是否可以从android中的位图中删除透明像素

标签 android bitmap

在我的应用程序中,如果图像没有填满 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);
}

关于android - 是否可以从android中的位图中删除透明像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16895945/

相关文章:

c# - 在 C# 中读取打印机设备上下文

java - 在 Java 中绘制位图

java - 该应用程序可能在其主线程中执行了过多的工作

android - Servlet 与 Hibernate 通信

java - 试图缩小 Android 中的位图不起作用

canvas - 如何更改画架中的位图宽度和高度?

android - 如何在保留颜色的同时将 Mat 对象转换为位图?

android - 将来自 url 的图像添加到自定义 InfoWindow google maps v2

android - Android 中 ListView 底部的按钮

android - fitsSystemWindows 在添加的 fragment 中不起作用