Skip to content

Instantly share code, notes, and snippets.

@ibrahimsn98
Created January 27, 2018 21:04
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibrahimsn98/ba19bbaf5b5e67813657ec3e046c14f2 to your computer and use it in GitHub Desktop.
Save ibrahimsn98/ba19bbaf5b5e67813657ec3e046c14f2 to your computer and use it in GitHub Desktop.
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