在android应用程序中将alpha应用于jpeg的更快方法



我使用png文件启动了我的android应用程序,用于需要alpha的对象,但我很快意识到所需的空间太大了。所以,我写了一个程序,用alpha生成了一个png,并创建了一个b&w阿尔法掩码png文件和jpeg。这给了我巨大的空间节省,但速度不是很快。

以下是我的Android应用程序中的代码,它结合了jpg图像(代码中的origImgId)和png掩码(代码中)。

它有效,但不快。我已经缓存了结果,我正在编写代码,在游戏开始前将这些图像加载到菜单屏幕中,但如果有办法加快速度,那就太好了。

有人有什么建议吗?请注意,我稍微修改了代码,使其易于理解。在游戏中,这实际上是一个精灵,它根据需要加载图像并缓存结果。在这里,您只看到加载图像和应用alpha的代码。

public class BitmapDrawableAlpha
{
    public BitmapDrawableAlpha(int origImgId, int alphaImgId) {
        this.origImgId = origImgId;
        this.alphaImgId = alphaImgId;
    }
    protected BitmapDrawable loadDrawable(Activity a) {
        Drawable d = a.getResources().getDrawable(origImgId);
        Drawable da = a.getResources().getDrawable(alphaImgId);
        Bitmap b = Bitmap.createBitmap(d.getIntrinsicWidth(),d.getIntrinsicHeight(),Bitmap.Config.ARGB_8888);
        {
            Canvas c = new Canvas(b);
            d.setBounds(0,0,d.getIntrinsicWidth()-1,d.getIntrinsicHeight()-1);
            d.draw(c);
        }
        Bitmap ba = Bitmap.createBitmap(d.getIntrinsicWidth(),d.getIntrinsicHeight(),Bitmap.Config.ARGB_8888);
        {
            Canvas c = new Canvas(ba);
            da.setBounds(0,0,d.getIntrinsicWidth()-1,d.getIntrinsicHeight()-1);
            da.draw(c);
        }
        applyAlpha(b,ba);
        return new BitmapDrawable(b);
    }
    /** Apply alpha to the specified bitmap b. */
    public static void applyAlpha(Bitmap b, Bitmap bAlpha) {
        int w = b.getWidth();
        int h = b.getHeight();
        for(int y=0; y < h; ++y) {
            for(int x=0; x < w; ++x) {
                int pixel = b.getPixel(x,y);
                int finalPixel = Color.argb(Color.alpha(bAlpha.getPixel(x,y)), Color.red(pixel), Color.green(pixel), Color.blue(pixel));
                b.setPixel(x,y,finalPixel);
            }
        }
    }
    private int origImgId;
    private int alphaImgId;
}

如果要对每个多个像素进行操作,可以调用getPixels()和setPixel()一次获取所有像素。这将防止循环中出现额外的方法调用和内存引用。

您可以做的另一件事是使用逐位或代替辅助方法进行像素相加。防止方法调用应提高效率:

public static void applyAlpha(Bitmap b, Bitmap bAlpha) {
    int w = b.getWidth();
    int h = b.getHeight();
    int[] colorPixels = new int[w*h];
    int[] alphaPixels = new int[w*h];
    b.getPixels(colorPixels, 0, w, 0, 0, w, h);
    bAlpha.getPixels(alphaPixels, 0, w, 0, 0, w, h);
    for(int j = 0; j < colorPixels.length;j++){
        colorPixels[j] = alphaPixels[j] | (0x00FFFFFF & colorPixels[j]);
    }
    b.setPixels(colorPixels, 0, w, 0, 0, w, h);
}

话虽如此,你尝试进行的过程相当简单,我无法想象这些会带来巨大的性能提升。从这一点来看,我能提供的唯一建议是使用NDK来实现本机。

编辑:此外,由于位图不必是可变的才能使用getPixels()getPixel(),因此可以使用BitmapFactory.decodeResource():获得alpha位图

Bitmap ba = BitmapFactory.decodeResource(a.getResources(), alphaImgId);

最新更新