如何从xml中定义的可绘制对象获取位图?

问题描述:

如何从xml形状可绘制对象获取位图. 我在做什么错了?

How can I get the bitmap from a xml shape drawable. What am I doing wrong?

shadow.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检索位图的方法:

My method to retrieve the bitmap from drawable:

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

当传入的ID为 shadow.xml 可绘制的ID时,

getBitmap()返回null.

getBitmap() is returning null when the id passed in is the shadow.xml drawable id.

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

a ShapeDrawable doesn't have a bitmap associated with it - its sole purpose is to be drawn on a canvas. Until its draw method is called, it has no image. If you can get a canvas element at the place where you need to draw the shadow, you can draw it as a shapeDrawable, otherwise you might need a separate, empty view in your layout with the shadow as a background.