Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android - Get aplication's adaptive icons in circle form
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
public class IconHelper {
private PackageManager packageManager;
public IconHelper(PackageManager packageManager) {
this.packageManager = packageManager;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public Bitmap getAppIcon(String packageName) {
try {
Drawable drawable = packageManager.getApplicationIcon(packageName);
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else {
if (drawable instanceof AdaptiveIconDrawable) {
AdaptiveIconDrawable aid = ((AdaptiveIconDrawable) drawable);
Drawable[] drr = new Drawable[2];
drr[0] = aid.getBackground();
drr[1] = aid.getForeground();
LayerDrawable layerDrawable = new LayerDrawable(drr);
int width = layerDrawable.getIntrinsicWidth();
int height = layerDrawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
layerDrawable.draw(canvas);
bitmap = GetBitmapClippedCircle(bitmap);
return bitmap;
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
private Bitmap GetBitmapClippedCircle(Bitmap bitmap) {
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
final Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Path path = new Path();
path.addCircle(
(float)(width / 2)
, (float)(height / 2)
, (float) Math.min(width, (height / 2))
, Path.Direction.CCW);
final Canvas canvas = new Canvas(outputBitmap);
canvas.clipPath(path);
canvas.drawBitmap(bitmap, 0, 0, null);
return outputBitmap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.