How to create a circular ImageView in Android? [duplicate]
Asked Answered
I

1

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?

Imperturbable answered 25/4, 2013 at 7:1 Comment(9)
this code may help you. Edit it according to your needs. https://mcmap.net/q/50038/-how-to-make-an-imageview-with-rounded-cornersYelmene
@IceMAN i dont want to make rounded corners i need to set image inside circleImperturbable
@D'yerMak'er thanks but i want to set the image in circle imageviewImperturbable
Your post title reads rounded!!Wiser
@IceMAN yes.. i have attached the image what i need to do..could you help me outImperturbable
Just use the CircularImageView Library "github.com/lopspower/CircularImageView" and its working like a charm in my caseTennyson
i have done this using the answer below but different logic see this link #21872333Remde
Nowadays the preferred solution should be RoundedBitmapDrawable; it's nice and simple, and part of official support libs (since v4 Support Library revision 21).Thrower
Nowadays Material Design 1.2.0 introduced ShapeableImageView.Pittance
R
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;
    }

}
Ragwort answered 25/4, 2013 at 7:13 Comment(34)
is it working fine PermitaImperturbable
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 ....Imperturbable
What is package name of "ImageUtils"? I cannot find it and IDE made it red :(Valina
thats a custom package and a custom method for innershadow. I didnt mentioned about it as it was not asked in the question.Ragwort
Sorry if I am accidentally bumping an old post, but I would like the code for the drop shadow and the white outline if possibleClaycomb
@Ragwort i have some clarification regarding this question can you help me..Imperturbable
@Ragwort while i m getting the image from gallery it not getting rounded..but from camera the image is getting rounded..any idea..Imperturbable
priya can you add your code?Ragwort
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?Dup
this view is great but it distort not-square images, I fix that here: gist.github.com/melanke/7158342Sylvia
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 ????Rend
I was able to use @melanke's gist with NetworkImageView from Volley.Biocatalyst
@Ragwort Don't do too much of work in onDraw() callback as it is called for many times as screen updates!!!Hasa
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 #2460416Terrenceterrene
A little correction: Insert in the onDraw method after get the bitmap. if(b == null) return;Sized
Please tell me how to use the above code for Rounded ImageView. Any example line of code to implement it.Agnew
I've noticed that Google has "RoundedBitmapDrawableFactory" . I think it can be useful.Park
@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?Multicellular
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?Thessalonian
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.Wendel
Just use the CircularImageView Library "github.com/lopspower/CircularImageView" and its working like a charm in my caseTennyson
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.Ledge
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.Dioecious
Upvoted. Works awesome, just wanted to point out the variable name 'radius' in the method 'getCroppedBitmap' should be diameter.Yingling
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.Ciliata
@RudyRudolf So you suggest making the canva a field of the class then ?Grantland
@Grantland here is gist from my project. gist.github.com/pjakubczyk/5dc2e95739286e2ce186 :)Ciliata
@Ragwort could you update your snippet for better performance?Ciliata
The type AvoidXfermode.Mode is deprecatedAntisemite
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=<h) { canvas.drawBitmap(sbmp, 0, -(h-w) / 2, paint);Lolland
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)Lollop
@Ragwort Your custom class cause of resize image, see this image rupload.ir/upload/y73c1pt579y8uj6xu8ua.pngTapioca
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 zoomedLytle
please use this https://mcmap.net/q/99766/-imageview-in-circular-through-xmlKnighterrantry

© 2022 - 2024 — McMap. All rights reserved.