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

mol*_*mol 37 android xml-drawable android-drawable

我查看了多个类似的问题,虽然我的查询没有找到正确的答案.

我有一个drawable,在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>
Run Code Online (Sandbox Code Playgroud)

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

这就是我这样做的方式:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?是BitmapFactory.decodeResource()适用于XML定义可绘制?

Phi*_*oda 65

由于您要加载a Drawable而不是a Bitmap,请使用以下命令:

Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);
Run Code Online (Sandbox Code Playgroud)

把它变成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;
}
Run Code Online (Sandbox Code Playgroud)

摘自:如何将Drawable转换为位图?

  • 我想知道这是如何工作的......因为drawable是用XML定义的形状,`getIntrinsicWidth()`和`getIntrinsicHeight()`总是返回-1并且不会创建位图.还是我弄错了? (5认同)
  • 抛出`IllegalArgumentException:width和height必须> 0` (3认同)
  • 使用新的支持库进行更新:使用ContextCompat.GetDrawable(context,id) (2认同)
  • Drawable类的Koltin扩展名:[https://gist.github.com/gowthamgts/9d496f42ce0acd16194641f69fcc48a6](https://gist.github.com/gowthamgts/9d496f42ce0acd16194641f69fcc48a6) (2认同)

小智 9

Android KTX现在具有将可绘制对象转换为位图的扩展功能

val bitmap = ContextCompat.getDrawable(context, R.drawable.ic_user_location_pin)?.toBitmap()

if (bitmap != null) {
    markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
}
Run Code Online (Sandbox Code Playgroud)