With the new preview release yesterday I started to update my app to this version. Part of my app is to list installed applications with the associated icons.
Drawable drawable = mPackageManager.getApplicationIcon(packageName);
This part of the app still works. Apps like the clock, calculator or messages already support the new version of icons, so they return a AdaptiveIconDrawable
.
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
This part doesn't work anymore. Is there any other way to convert AdaptiveIconDrawable
to a Bitmap
? Thanks in advance.
This example demonstrates how do I convert Drawable to a Bitmap in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory.
A bitmap (or raster graphic) is a digital image composed of a matrix of dots. When viewed at 100%, each dot corresponds to an individual pixel on a display. In a standard bitmap image, each dot can be assigned a different color. In this instance we will simply create a Bitmap directly: Bitmap b = Bitmap.
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.
This is much more universal solution:
@NonNull
private Bitmap getBitmapFromDrawable(@NonNull Drawable drawable) {
final Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bmp;
}
It will also render background in the system defined shape, if you don't want to use own.
You can use it on any Drawable, so also for VectorDrawable. It will works also on BitmapDrawable, just getBitmap() will be more memory efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With