Android ImageView 中的透明 GIF [英] Transparent GIF in Android ImageView

查看:30
本文介绍了Android ImageView 中的透明 GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的应用程序中显示透明的 GIF 图像,但没有成功.我可以下载并在 ImageView 中显示图标,但使用白色背景而不是透明.

I am trying to display the transparent GIF image in my app with no success. I can get to download and display the icon in an ImageView but with white background instead of transparent.

我已经尝试了这些解决方案但没有成功:以编程方式将 GIF 转换为 PNG

I have already tried these solutions with no sucess: Convert GIF to PNG programatically

有人知道如何以透明方式显示 GIF 图像吗?我正在使用 Android 18 SDK.

Has anyone figured out how to display the GIF image with transparency? I am using the Android 18 SDK.

推荐答案

这是一个对我有用的解决方法.这不是一个好的解决方案.它可能不适用于所有情况,并且在图像处理中存在大量开销.希望其他人能找到更好的解决方案.

Here is a workaround that has worked for me. It is not a good solution. It may not work in all cases and there is significant overhead in image processing. Hopefully someone else will find a better solution.

在我的测试中,4.4 中的 GIF 图像具有白色 (-1) 或黑色 (-16777216) 的透明度值.加载位图后,您可以将白色/黑色像素转换回透明.当然,这仅在图像的其余部分不使用相同颜色时才有效.如果是这样,那么您还将图像的某些部分转换为原始图像中不透明的透明部分.就我而言,这不是问题.

In my testing, GIF images in 4.4 have transparency values as either white (-1) or black (-16777216). After you load a Bitmap, you can convert the white/black pixels back to transparent. Of course this will only work if the rest of the image doesn't use the same color. If it does then you will also convert parts of your image to transparent that were not transparent in the original image. In my case this wasn't a problem.

您可以使用以下代码将白色或黑色像素转换为透明.

You can use the following code to convert either white or black pixels to transparent.

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap = eraseBG(bitmap, -1);         // use for white background
bitmap = eraseBG(bitmap, -16777216);  // use for black background


private static Bitmap eraseBG(Bitmap src, int color) {
    int width = src.getWidth();
    int height = src.getHeight();
    Bitmap b = src.copy(Config.ARGB_8888, true);
    b.setHasAlpha(true);

    int[] pixels = new int[width * height];
    src.getPixels(pixels, 0, width, 0, 0, width, height);

    for (int i = 0; i < width * height; i++) {
        if (pixels[i] == color) {
            pixels[i] = 0;
        }
    }

    b.setPixels(pixels, 0, width, 0, 0, width, height);

    return b;
}

注意:我必须将位图复制到新的 ARGB_8888 图像才能工作.即使将位图加载为可变的,我仍然无法修改像素.这也是开销如此之大的部分原因.

Note: I had to copy the Bitmap to a new ARGB_8888 image for this to work. Even when loading the bitmap as mutable, I still couldn't modify the pixels. This is partly why there is so much overhead.

这篇关于Android ImageView 中的透明 GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆