ImageView 中的 PNG 有黑色背景

Lei*_*yba 2 android android-imageview

我的图像视图设置为一个 PNG 位图。但问题是透明部分是黑色的。我已经将背景设置为@android:color/transparent 和 #00000000,但它仍然是黑色的。我试图搜索,但没有任何帮助。提前致谢!

这是带有父级的 imageView 的 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/mainbg"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/vbTempLink"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="15"
        android:background="@color/mainbg"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="10"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/tempImage1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="25"
                android:background="@android:color/transparent"
                android:gravity="center"
                android:paddingBottom="5dp"
                android:paddingTop="5dp"
                android:scaleType="fitCenter" />
Run Code Online (Sandbox Code Playgroud)

我用这些代码设置了 png(bg 是字符串):

background.setBackgroundDrawable(bitmapToDrawable((bg)));

public Drawable bitmapToDrawable(String s) {
    Bitmap bitmap = BitmapFactory.decodeFile(path + s);
    Drawable drawable = new BitmapDrawable(getResources(), bitmap);
    return drawable;
}
Run Code Online (Sandbox Code Playgroud)

是的,图像肯定有透明背景。

小智 5

我知道这是很老的帖子,但这可能会帮助其他人..

从您的代码中,我可以清楚地看到您是从本地存储而不是从 Android 资源中检索图像。

Bitmap bitmap = BitmapFactory.decodeFile(path + s);
Run Code Online (Sandbox Code Playgroud)

所以我认为您正在尝试检索 JPEG 压缩图像。如果文件扩展名以其他压缩格式存储,则文件扩展名毫无意义

如果要存储和检索 PNG 图像,请以 PNG 格式存储源图像,然后检索它。

bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Run Code Online (Sandbox Code Playgroud)

因为默认情况下 JPEG 压缩会将透明背景像素存储为黑色。所以最好避免将其压缩为 JPEG。