更快速地设置(PNG)位图颜色而不是逐像素

时间:2010-11-22 22:52:32

标签: java android colors

我有一些png文件,我正在应用颜色。颜色根据用户选择而变化。我通过另一种方法设置的3个RGB值更改颜色。 png文件是随机形状,在形状外部具有完全透明度。我不想修改透明度,只修改RGB值。目前,我正在逐像素设置RGB值(参见下面的代码)。

我已经意识到这非常缓慢,并且在应用程序中可能效率不高。我有更好的办法吗?

这是我目前正在做的事情。您可以看到像素阵列对于占据屏幕相当一部分的图像来说是巨大的:

public void foo(Component component, ComponentColor compColor, int userColor) {
    int h = component.getImages().getHeight();
    int w = component.getImages().getWidth();
    mBitmap = component.getImages().createScaledBitmap(component.getImages(), w, h, true);

    int[] pixels = new int[h * w];

    //Get all the pixels from the image
    mBitmap[index].getPixels(pixels, 0, w, 0, 0, w, h);

    //Modify the pixel array to the color the user selected
    pixels = changeColor(compColor, pixels);

    //Set the image to use the new pixel array
    mBitmap[index].setPixels(pixels, 0, w, 0, 0, w, h);
}

public int[] changeColor(ComponentColor compColor, int[] pixels) {
    int red = compColor.getRed();
    int green = compColor.getGreen();
    int blue = compColor.getBlue();
    int alpha;

    for (int i=0; i < pixels.length; i++) {
        alpha = Color.alpha(pixels[i]);
        if (alpha != 0) {
            pixels[i] = Color.argb(alpha, red, green, blue);
        }
    }
    return pixels;
}

2 个答案:

答案 0 :(得分:2)

您是否查看了Bitmap中可用的功能?像extractAlpha这样的东西听起来可能有用。您还可以查看Android中实现的功能,以了解如何根据您的需求调整特定情况。

答案 1 :(得分:1)

对我有用的答案是在这里写了一篇Square Transparent jpegs

他们提供了一个更快的代码片段来完成这件事。我尝试过extractAlpha并且它没有用,但Square的解决方案确实如此。只需修改他们的解决方案,而不是修改颜色位而不是alpha位。

pixels[x] = (pixels[x] & 0xFF000000) | (color & 0x00FFFFFF);
相关问题