Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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> 

My method to retrieve the bitmap from drawable:

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

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

like image 332
kaneda Avatar asked Apr 11 '12 17:04

kaneda


People also ask

How do I get bitmap from imageView?

Bitmap bm=((BitmapDrawable)imageView. getDrawable()). getBitmap(); Try having the image in all drawable qualities folders (drawable-hdpi/drawable-ldpi etc.)

What is bitmap drawable?

android.graphics.drawable.BitmapDrawable. A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a BitmapDrawable from a file path, an input stream, through XML inflation, or from a Bitmap object. It can be defined in an XML file with the <bitmap> element.


2 Answers

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> 
like image 74
vovahost Avatar answered Sep 21 '22 07:09

vovahost


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.

like image 30
JRaymond Avatar answered Sep 22 '22 07:09

JRaymond