我正在使用以下方法从我的 Android 应用程序的 Assets 文件夹中提取 PNG 文件:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
然后我将 ImageView 的源(在 GridView 的项目中)设置为该位图。
这里是有问题的布局 XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/containingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:background="@android:color/transparent"
android:padding="0dp"
android:layout_margin="0dp"
>
<ImageView
android:id="@+id/ivPackageIcon"
style="@style/smLargeGridItemPackageIconStyle"
/>
</LinearLayout>
该 XML 中引用的样式是:
<style name="smLargeGridItemPackageIconStyle">
<item name="android:scaleType">fitXY</item>
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">142dp</item>
<item name="android:layout_margin">5dp</item>
<item name="android:background">@android:color/transparent</item>
</style>
这是设置 ImageView 源的代码:
ImageView ivPackageIcon = (ImageView)containingView.findViewById(R.id.ivPackageIcon);
if(ivPackageIcon != null) {
Bitmap coverImage = getBitmapFromAssets(containingView.getContext(), "myimage.png");
ivPackageIcon.setImageBitmap(coverImage);
}
PNG 图像有一些透明区域,但由于某种原因,当图像显示在我的 GridView 中时,透明区域显示为黑色。
抢先一些问题:不是,Activity、ImageView、GridView、GridView item的背景都不是黑色的。事实上,无论设置什么背景颜色,图像的透明部分总是呈现黑色。
不过请考虑一下...如果我将 PNG 图像放在可绘制文件夹中并按如下方式设置 ImageView,透明度是完美的:
ivPackageIcon.setImageResource(R.drawable.myimage);
我很确定我以某种方式错误地使用了 decodeStream(...) 方法,但我不知道我做错了什么。我什至修改了我原来的方法来设置一些选项,如下所示:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
但这给了我同样糟糕的结果。
任何想法,任何人?
谢谢。
最佳答案
代替这个,试试:
ImageView img=new ImageView(this);
Drawable d = Drawable.createFromStream(getAssets().open(path_in_assets), null);
img.setImageDrawable(d);
关于Android:使用 BitmapFactory.decodeStream(...) 和 Assets 文件夹时 PNG 透明度失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9092064/