代码之家  ›  专栏  ›  技术社区  ›  user432209

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

  •  1
  • user432209  · 技术社区  · 14 年前

    我有一些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 回复  |  直到 14 年前
        1
  •  2
  •   Cheryl Simon    14 年前

    你看过 Bitmap ? 有点像 extractAlpha 听起来可能有用。你还可以看看类似的功能在Android中的实现方式,看看如果它不能完全满足你的需求,你如何使它适应你的特定情况。

        2
  •  1
  •   Daniel Ochoa    10 年前

    对我有用的答案是这里写的一个正方形 Transparent jpegs

    它们提供了一个更快的代码片段来完成这项工作。我试着用提拉法,但没用,但Square的解决方案成功了。只需修改他们的解决方案,而不是修改颜色位而不是alpha位。

    pixels[x] = (pixels[x] & 0xFF000000) | (color & 0x00FFFFFF);