I try to convert layer-list
to bitmap
, then set this bitmap
as a background for an ImageView
but it not working
This is a test project. I know I can set drawable directly to ImageView, but I want to know why when I convert LayerDrawable
to Bitmap
then convert Bitmap
to BitmapDrawable
then set it as background of ImageView, it will look different
Here is my layer-list (ic_circle.xml)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
>
<item>
<shape
android:shape="oval">
<solid android:color="#f00"></solid>
</shape>
</item>
<item
android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp">
<shape
android:shape="oval">
<solid android:color="#ff0"></solid>
</shape>
</item>
<item
android:bottom="6dp" android:left="6dp" android:right="6dp" android:top="6dp">
<shape
android:shape="oval">
<solid android:color="#0ff"></solid>
</shape>
</item>
</layer-list>
Activity code
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.img);
Bitmap bm = drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.ic_circle));
img.setBackground(new BitmapDrawable(bm));
}
public Bitmap drawableToBitmap (Drawable drawable) {
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
Xml code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:background="@drawable/ic_circle"
/>
<ImageView
android:id="@+id/img"
android:layout_marginTop="40dp"
android:layout_width="80dp"
android:layout_height="80dp"
/>
</LinearLayout>
In the emulator, you will see the second image is different to first image
In your drawable you have you have defined only boundaries of 2 outer small circles (yellow and red), and the blue one should take all the rest space. But since it has no defined size, once you draw it on the canvas, it's size will be 0.
You have to define it's size as well if you want to draw it directly on the bitmap.