gpt4 book ai didi

android - BitmapFactory.decodeResource() 为 xml drawable 中定义的形状返回 null

转载 作者:IT老高 更新时间:2023-10-28 21:40:30 27 4
gpt4 key购买 nike

我查看了多个类似的问题,尽管我没有找到适合我的问题的答案。

我有一个在 shape.xml 中定义的可绘制对象

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >

<solid android:color="@color/bg_color" />
</shape>

我想将它转换为Bitmap对象以执行一些操作,但是BitmapFactory.decodeResource()返回null。

这就是我的做法:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);

我做错了什么? BitmapFactory.decodeResource() 是否适用于 xml 定义的可绘制对象?

最佳答案

由于您要加载 Drawable,而不是 Bitmap,因此请使用:

Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);

把它变成一个Bitmap:

public static Bitmap drawableToBitmap (Drawable drawable) {

if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}

Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

return bitmap;
}

取自:How to convert a Drawable to a Bitmap?

关于android - BitmapFactory.decodeResource() 为 xml drawable 中定义的形状返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24389043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com