Search code examples
androiduniversal-image-loaderandroid-bitmap

Circular bitmap with Universal Image Loader


We are showing a notification with a large icon get from an URL. So, in order to load the image we are using Universal Image Loader with the following code:

mImageLoader.loadImage(imagePath, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            notificationBuilder.setLargeIcon(loadedImage);
            notificationManager.notify(notification.getId(), notificationBuilder.build());
        }
});

This code is working fine and the image is successfully shown. Our problem is that we want to show a circular large icon, so we need the bitmap to be circular. We have tried by setting:

    final DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(1000))
            .build();

But this is not working, we've tried with RoundedBitmapDrawable, but we need a bitmap and not a bitmapdrawable. Please, how could we do in order to get a circular bitmap?

Thanks in advance.


Solution

  • Try this:

     public static Bitmap getCircularBitmap(Bitmap bitmap) {
        Bitmap output;
    
        if (bitmap.getWidth() > bitmap.getHeight()) {
            output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Config.ARGB_8888);
        } else {
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Config.ARGB_8888);
        }
    
        Canvas canvas = new Canvas(output);
    
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    
        float r = 0;
    
        if (bitmap.getWidth() > bitmap.getHeight()) {
            r = bitmap.getHeight() / 2;
        } else {
            r = bitmap.getWidth() / 2;
        }
    
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(r, r, r, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }