How to get a Bitmap from a drawable defined in a xml?

前端 未结 3 1872
余生分开走
余生分开走 2020-12-24 05:20

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

shadow.xml



        
相关标签:
3条回答
  • 2020-12-24 05:39

    You should add size attribute to your shape drawable for preventing "java.lang.IllegalArgumentException: width and height must be > 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>
    
    0 讨论(0)
  • 2020-12-24 05:43

    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.

    0 讨论(0)
  • 2020-12-24 05:49

    This is a fully working solution:

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

    And here is an example:

    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>
    
    0 讨论(0)
提交回复
热议问题