Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert AdaptiveIconDrawable to Bitmap in Android O preview

Tags:

android

bitmap

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.

like image 942
GoKo Avatar asked Jun 08 '17 23:06

GoKo


People also ask

How do I make a drawable Bitmap?

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.

How do I create a Bitmap in Kotlin?

To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory.

What is bitmap image in Android?

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.

What is a 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.


1 Answers

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.

like image 170
ATom Avatar answered Sep 30 '22 20:09

ATom