本文介绍了BitmapFactory.decodeResource()对于xml drawable中定义的形状返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管没有在我的查询中找到正确的答案,但我还是浏览了多个类似的问题.

I looked through multiple similar questions, although I haven't found proper answer on my query.

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

I have a drawable, defined in 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.

I want to convert it to Bitmap object in order to perform some operations, but BitmapFactory.decodeResource() returns null.

这就是我的做法:

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

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

What am I doing wrong? Is BitmapFactory.decodeResource() applicable for xml defined drawables?

推荐答案

由于要加载Drawable而不是Bitmap,请使用以下方法:

Since you want to load a Drawable, not a Bitmap, use this:

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;
}

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

这篇关于BitmapFactory.decodeResource()对于xml drawable中定义的形状返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:40