256

How could I create a rounded ImageView in Android?

I have tried the following code, but it's not working fine.

Code:

Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

BitmapShader shader = new BitmapShader (bitmap,  TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);

Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);

imageView.setImageBitmap(circleBitmap);

Image inside the circle:

Enter image description here

How can I do this?

Jonik
  • 80,077
  • 70
  • 264
  • 372
  • this code may help you. Edit it according to your needs. http://stackoverflow.com/a/3292810/2021499 – D'yer Mak'er Apr 25 '13 at 07:04
  • @IceMAN i dont want to make rounded corners i need to set image inside circle –  Apr 25 '13 at 07:11
  • @D'yerMak'er thanks but i want to set the image in circle imageview –  Apr 25 '13 at 07:12
  • 1
    Your post title reads **rounded!!** – Siddharth Lele Apr 25 '13 at 07:27
  • @IceMAN yes.. i have attached the image what i need to do..could you help me out –  Apr 25 '13 at 07:32
  • 3
    Just use the CircularImageView Library "https://github.com/lopspower/CircularImageView" and its working like a charm in my case – Naveed Ahmad Mar 04 '15 at 14:17
  • i have done this using the answer below but different logic see this link http://stackoverflow.com/questions/21871833/making-an-image-circular-with-white-circular-border/32346187#32346187 – Syed Raza Mehdi Sep 02 '15 at 06:41
  • 2
    Nowadays the preferred solution should be **[RoundedBitmapDrawable](http://stackoverflow.com/a/26471808/56285)**; it's nice and simple, and part of official support libs (since v4 Support Library revision 21). – Jonik Jun 13 '16 at 14:22
  • Nowadays Material Design 1.2.0 introduced **[ShapeableImageView](https://stackoverflow.com/questions/66138001/imageview-with-only-bottom-or-top-corners-rounded/66138444#66138444)**. – Ali Feb 11 '21 at 06:21

1 Answers1

432

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
Permita
  • 5,503
  • 1
  • 16
  • 21
  • is it working fine Permita –  Apr 25 '13 at 07:14
  • Permita thanks ,i have tried your code, it shows oval imageview, do you know how could i make it rounded with border ,anyway i accept your answer,if you have any idea to make perfect circular image view then kindly help me .... –  May 24 '13 at 13:33
  • What is package name of "ImageUtils"? I cannot find it and IDE made it red :( – Hesam May 31 '13 at 03:54
  • thats a custom package and a custom method for innershadow. I didnt mentioned about it as it was not asked in the question. – Permita May 31 '13 at 05:49
  • Sorry if I am accidentally bumping an old post, but I would like the code for the drop shadow and the white outline if possible – Excalibur Jun 09 '13 at 12:32
  • @Permita i have some clarification regarding this question can you help me.. –  Jul 19 '13 at 09:17
  • @Permita while i m getting the image from gallery it not getting rounded..but from camera the image is getting rounded..any idea.. –  Jul 20 '13 at 07:15
  • priya can you add your code? – Permita Jul 20 '13 at 12:17
  • Hi Permita, I am looking for a library or a solution on how to add the white border to the rounded final image, so exactly the function that you are referring in the line `ImageUtils.setCircularInnerGlow()`. Can you recommend a library for that or share some code please? – Stefan Anca Aug 21 '13 at 16:31
  • 72
    this view is great but it distort not-square images, I fix that here: https://gist.github.com/melanke/7158342 – melanke Oct 25 '13 at 17:20
  • The image is having black background after rounding, I tried to change it to some other color, but was not able to do, any help ???? – viv Oct 26 '13 at 13:02
  • I was able to use @melanke's gist with NetworkImageView from Volley. – MCR Feb 11 '14 at 15:26
  • @Permita Don't do too much of work in `onDraw()` callback as it is called for many times as screen updates!!! – Gopal Gopi Mar 26 '14 at 05:03
  • 4
    This may cause OOM due to onDraw() execute to many times.When create a large circular image say 200*200(dip) in tab. So Use a image loader libraries to load a circle a image. Please see http://stackoverflow.com/questions/2459916/how-to-make-an-imageview-to-have-rounded-corners/23885808#23885808 – shailesh Jun 06 '14 at 12:13
  • A little correction: Insert in the onDraw method after get the bitmap. if(b == null) return; – Felipe Porge Xavier Jul 02 '14 at 17:01
  • Please tell me how to use the above code for Rounded ImageView. Any example line of code to implement it. – Usman Khan Dec 16 '14 at 12:55
  • 17
    I've noticed that Google has "RoundedBitmapDrawableFactory" . I think it can be useful. – android developer Dec 23 '14 at 12:51
  • @melanke: The code is pretty good. One problem for me is the round circle always is on the left side of the original image. Do you have an idea to get the view-circle in center? – softwaresupply Jan 06 '15 at 14:45
  • i have a problem! i am using this as an custom view in a grid view. the `b` variable in `b.copy(...)` is null some time. what? – mahdi Jan 12 '15 at 15:54
  • 3
    Is it just me or does the code mix radius and diameter? So, in some places radius is needed (drawCircle), but when setting the bitmap dimensions, the diameter should be used, not the radius. – Eran Boudjnah Feb 07 '15 at 11:33
  • Just use the CircularImageView Library "https://github.com/lopspower/CircularImageView" and its working like a charm in my case – Naveed Ahmad Mar 04 '15 at 14:17
  • What is the point of adding 0.7f and 0.1f? That resulted in the bottom of my images being slightly cut off. Removing them fixed the problem. – bmat Mar 12 '15 at 02:49
  • 3
    May I suggest: Bitmap roundBitmap = getCroppedBitmap(bitmap, w < h ? w : h); So that if the imageview isn't square it always shows the entire image. – Daan Luttik Aug 02 '15 at 14:08
  • Upvoted. Works awesome, just wanted to point out the variable name 'radius' in the method 'getCroppedBitmap' should be diameter. – jasxir Oct 07 '15 at 01:57
  • 1
    During onDraw is a bad idea. I'd suggest to override setImageDrawable or setImageBitmap and do the calculation there since it's called only once. – Rudy Rudolf Nov 06 '15 at 12:58
  • @RudyRudolf So you suggest making the canva a field of the class then ? – Ced Dec 04 '15 at 20:27
  • @Ced here is gist from my project. https://gist.github.com/pjakubczyk/5dc2e95739286e2ce186 :) – Rudy Rudolf Dec 06 '15 at 15:39
  • @Permita could you update your snippet for better performance? – Rudy Rudolf Dec 22 '15 at 13:21
  • The type AvoidXfermode.Mode is deprecated – Aesthetic Mar 20 '16 at 01:04
  • to center the image I instead of rectangle version at the end do: if (w>h) { canvas.drawBitmap(sbmp, -(w-h) / 2, 0, paint); } else if (w= – Alex Martian Apr 10 '16 at 14:42
  • It seems that the issue with this method is that if the CustomImageView have a dynamic image affectation, it will not work. Let's say I create my object. The onDraw method called, the Drawable is null. Then, I assign to my object a Drawable with the setBackground() method. The onDraw is not called again (verified with debugger) – Alex Aug 29 '16 at 10:06
  • 1
    @Permita Your custom class cause of resize image, see this image http://rupload.ir/upload/y73c1pt579y8uj6xu8ua.png – mahdi pishguy Oct 05 '16 at 06:49
  • why is `int w = getWidth();` returning a value which is 3 times my `layout_width` ? as a result the rounded imageview is getting larger than the layout_width and the image is getting zoomed – mrid Aug 13 '17 at 08:10
  • please use this https://stackoverflow.com/a/61986850/9802543 – Moses Wangira Jun 25 '22 at 19:56