加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

对于在xml drawable中定义的形状,android – BitmapFactory.deco

发布时间:2020-12-16 08:00:48 所属栏目:百科 来源:网络整理
导读:我看了很多类似的问题,虽然我没有找到正确的答案我的查询。 我有一个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
我看了很多类似的问题,虽然我没有找到正确的答案我的查询。

我有一个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>

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

这是我如何做的:

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

我究竟做错了什么? BitmapFactory.decodeResource()是否适用于xml定义的drawable?

由于您要加载Drawable而不是位图,请使用以下命令:
Drawable d = getResources().getDrawable(...);

把它变成一个位图:

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,canvas.getWidth(),canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读