48

如何从可绘制的 xml 形状中获取位图。我究竟做错了什么?

影子.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270.0"
        android:endColor="@android:color/transparent"
        android:startColor="#33000000"
        android:type="linear" />

    <size android:height="7.0dip" />

</shape>

我从drawable中检索位图的方法:

private Bitmap getBitmap(int id) {
    return BitmapFactory.decodeResource(getContext().getResources(), id);
}

当传入的 id 是shadow.xml可绘制 id时,getBitmap() 返回 null 。

4

3 回答 3

76

这是一个完全有效的解决方案

private Bitmap getBitmap(int drawableRes) {
    Drawable drawable = getResources().getDrawable(drawableRes);
    Canvas canvas = new Canvas();
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    canvas.setBitmap(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);

    return bitmap;
}

这是一个例子:

Bitmap drawableBitmap = getBitmap(R.drawable.circle_shape);

circle_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="15dp"
        android:height="15dp" />
    <solid
        android:color="#94f5b6" />
    <stroke
        android:width="2dp"
        android:color="#487b5a"/>
</shape>
于 2016-02-23T10:22:28.690 回答
14

ShapeDrawable 没有与之关联的位图 - 它的唯一目的是在画布上绘制。在调用它的 draw 方法之前,它没有图像。如果您可以在需要绘制阴影的地方获得一个画布元素,则可以将其绘制为 shapeDrawable,否则您可能需要在布局中以阴影作为背景单独的空视图。

于 2012-04-11T17:45:51.240 回答
4

您应该将 size 属性添加到您的 shape drawable 以防止“java.lang.IllegalArgumentException:宽度和高度必须 > 0”。

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
       <solid android:color="@color/colorAccent" />
       <stroke
           android:width="1.3dp"
           android:color="@color/white" />

       <size android:height="24dp" android:width="24dp"/>
</shape>
于 2017-07-11T13:58:25.600 回答