如何从xml中定义的drawable获取位图?

kan*_*eda 41 android

如何从xml形状drawable获取位图.我究竟做错了什么?

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>
Run Code Online (Sandbox Code Playgroud)

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

private Bitmap getBitmap(int id) {
    return BitmapFactory.decodeResource(getContext().getResources(), id);
}
Run Code Online (Sandbox Code Playgroud)

传入的id是shadow.xml drawable id 时,getBitmap()返回null .

vov*_*ost 62

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

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

这是一个例子:

Bitmap drawableBitmap = getBitmap(R.drawable.circle_shape);
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

  • 它抛出java.lang.IllegalArgumentException:width和height必须> 0 (2认同)

JRa*_*ond 14

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