704

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?


Note that from 2021 onwards, simply use ShapeableImageView

Fattie
  • 27,874
  • 70
  • 431
  • 719
michael
  • 106,540
  • 116
  • 246
  • 346
  • This might be helpful http://stackoverflow.com/questions/26850780/bitmap-circular-crop-in-android – Mangesh Jan 23 '16 at 16:19
  • Hidden below older, more complicated answers is what I think should be the accepted answer now: [RoundedBitmapDrawable](http://stackoverflow.com/a/26471808/56285), added in v4 Support Library revision 21. – Jonik Jun 08 '16 at 08:43
  • You may do it easiest way just using the CardView with an ImageView inside - look the example here http://stackoverflow.com/a/41479670/4516797 – Taras Vovkovych Mar 14 '17 at 15:12
  • [This](https://github.com/siyamed/android-shape-imageview) library is very useful. – grrigore Nov 10 '18 at 18:07
  • Check this now we have `ShapeableImageView` to make circular or rounded imageView https://stackoverflow.com/a/61086632/7666442 – AskNilesh Apr 08 '20 at 04:14
  • 4
    Material Design 1.2.0 introduced **[ShapeableImageView](https://stackoverflow.com/questions/66138001/imageview-with-only-bottom-or-top-corners-rounded/66138444#66138444)** So might be it's useful. – Ali Feb 11 '21 at 06:08
  • Use ShapeableImageView from Material Component Library. Check this answer https://stackoverflow.com/a/61960983/1362418 – Khaled Saifullah Mar 07 '22 at 04:35

58 Answers58

579

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

http://www.ruibm.com/?p=184

This isn't my code, but I've used it and it's works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

Final code looks like this:

package com.company.app.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;

public class ImageHelper {
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), 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());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}
SilentCloud
  • 1,677
  • 3
  • 9
  • 28
George Walters II
  • 6,109
  • 2
  • 18
  • 10
368

Another easy way is to use a CardView with the corner radius and an ImageView inside:

  <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:cardCornerRadius="8dp"
            android:layout_margin="5dp"
            android:elevation="10dp">

            <ImageView
                android:id="@+id/roundedImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/image"
                android:background="@color/white"
                android:scaleType="centerCrop"
                />
        </androidx.cardview.widget.CardView>

enter image description here

Taras Vovkovych
  • 4,062
  • 2
  • 16
  • 21
271

Clipping to rounded shapes was added to the View class in API 21.

Just do this:

  • Create a rounded shape drawable, something like this:

res/drawable/round_outline.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    ...
</shape>
  • Set the drawable as your ImageView's background: android:background="@drawable/round_outline"
  • According to this documentation, then all you need to do is add android:clipToOutline="true"

Unfortunately, there's a bug and that XML attribute is not recognized. Luckily, we can still set up clipping in Java:

  • In your activity or fragment: ImageView.setClipToOutline(true)

Here's what it will look like:

enter image description here

Note:

This method works for any drawable shape (not just rounded). It will clip the ImageView to whatever shape outline you've defined in your Drawable xml.

Special note about ImageViews

setClipToOutline() only works when the View's background is set to a shape drawable. If this background shape exists, View treats the shape's outline as the borders for clipping and shadowing purposes.

This means, if you want to use setClipToOutline() to round the corners on an ImageView, your image must be set using android:src instead of android:background (since background must be set to your rounded shape). If you MUST use background to set your image instead of src, you can use this workaround:

  • Create a layout and set its background to your shape drawable
  • Wrap that layout around your ImageView (with no padding)
  • The ImageView (including anything else in the layout) will now display with rounded layout shape.
hungryghost
  • 9,463
  • 3
  • 23
  • 36
217

While the above answer works, Romain Guy (a core Android developer) shows a better method in his blog which uses less memory by using a shader not creating a copy of the bitmap. The general gist of the functionality is here:

BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);

RectF rect = new RectF(0.0f, 0.0f, width, height);

// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);

The advantages of this over other methods is that it:

  • does not create a separate copy of the bitmap, which uses a lot of memory with large images [vs most of the other answers here]
  • supports antialisasing [vs clipPath method]
  • supports alpha [vs xfermode+porterduff method]
  • supports hardware acceleration [vs clipPath method]
  • only draws once to the canvas [vs xfermode and clippath methods]

I've created a RoundedImageView based off this code that wraps this logic into an ImageView and adds proper ScaleType support and an optional rounded border.

David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
vinc3m1
  • 4,075
  • 1
  • 26
  • 23
  • in your `/ example / res / layout / rounded_item.xml ` why do you specify an image src when all your sources are hardcoded ? Nice demo, just way overkill. – Someone Somewhere Mar 21 '13 at 00:29
  • your sample has a serious out-of-memory issue, just like the original sample of Romain Guy. I still don't know what causes it, but just like his code, this is a really hard thing to find. If you can't see a crash from the app because of OOM, you can rotate the app multiple times till it occurs (depends on your device, ROM, etc...) . I've reported about it in the past here: http://stackoverflow.com/questions/14109187/using-a-rounded-corners-drawable – android developer May 01 '13 at 07:39
  • also, this solution (that is written here) just doesn't work if you use it directly on a bitmap. you need to create a drawable that will use it. it doesn't really change the bitmap at all. tested on android 4.1 . – android developer May 01 '13 at 08:51
  • another issue is that if the image can't fit into its boundaries, and you use centerCrop, you won't see the rounded corners, probably because its effect runs on the original image and not on the one that is really shown. – android developer May 01 '13 at 09:42
  • 1
    Nobody else is reporting the out of memory issue, so it must be something you're doing outside of the code that is incorrect. The example correctly holds a limited set of bitmaps in the adapter **without** recreating them every time a view is drawn. The example shown here is a snippet of the draw() method in the Drawable, which uses the reference to the original bitmap it holds and works correctly. It is **not** meant to change the original bitmap, but only render it with rounded corners. Center crop works fine in the example as well. – vinc3m1 May 01 '13 at 18:36
  • Then you probably haven't tested it on enough configurations. about OOM , try rotating the screen multiple times. it uses more and more memory. about centerCrop, you probably haven't tried enough sample images, with different aspect ratio and different sizes than the size of the ImageView. – android developer May 07 '13 at 18:52
  • 1
    If you can provide screenshots or devices where it doesn't work, or even go as far as offering a fix and pull request, that would be most productive. I've tested rotating multiple times on my devices and memory stays the same. – vinc3m1 May 07 '13 at 21:20
  • How about if I want to only round some edges, but not all? – CQM Feb 27 '14 at 16:15
  • @CQM my library can't directly support that due to limitations of the canvas API: http://developer.android.com/reference/android/graphics/Canvas.html#drawRoundRect(android.graphics.RectF, float, float, android.graphics.Paint) You would have to use a different method that may or may not be hardware accelrated – vinc3m1 Mar 09 '14 at 09:25
  • 12
    Note that it won't work if the image size is above 2048 pixels. The shader doesn't support a texture to be larger than that. – Gábor Mar 25 '14 at 23:00
  • @eliocs I reverted your [revision](http://stackoverflow.com/revisions/15032283/7) because the whole idea is to use the BitmapShader to draw directly on the canvas so a second bitmap is not created. Your function would result in creating another Bitmap, which is useful in some situations but is actually what this code is trying to avoid. – vinc3m1 Oct 25 '14 at 00:46
  • @vinc3m1 Okay, then I'm missing something. Could you please explain how do you created the `canvas` object in your code? – eliocs Oct 27 '14 at 10:01
  • @eliocs this would be in the `onDraw` method in a custom Drawable or a View directly. Like I said it's not for every case, but you can draw a transformed version directly to the screen without creating a new Bitmap this way. Check out the RoundedImageView (specifically RoundedDrawable) source for an example. – vinc3m1 Oct 27 '14 at 21:50
  • @vinc3m1 Thanks for the explaination :). I would suggest that adding the `onDraw` signature on your code snippet would make the it clearer. – eliocs Oct 28 '14 at 09:56
  • Works perfectly out of the box, might want to change your xml example to reflect the new longer package path name though. – Mathijs Segers Mar 06 '15 at 14:16
  • And this solution doesn't help when you would need the Bitmap, to work more with it – Ultimo_m Feb 22 '19 at 14:27
  • how can i call this function to use it on my imageview? – Janessa Bautista Jan 28 '20 at 08:09
217

Starting with the version 1.2.0-alpha03 of the Material Components Library there is the new ShapeableImageView.

You can use something like:

<com.google.android.material.imageview.ShapeableImageView
    ...
    app:shapeAppearanceOverlay="@style/roundedImageView"
    app:srcCompat="@drawable/ic_image" />

with in your themes.xml:

<style name="roundedImageView" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
</style>

Or programmatically:

float radius = getResources().getDimension(R.dimen.default_corner_radius);
imageView.setShapeAppearanceModel(imageView.getShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,radius)
    .build());

enter image description here


With jetpack compose you can apply a clip Modifier using a RoundedCornerShape:

Image(
    painter = painterResource(R.drawable.xxxx),
    contentDescription = "xxxx",
    contentScale = ContentScale.Crop,            
    modifier = Modifier
        .size(64.dp)
        .clip(RoundedCornerShape(8.dp))             
)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
146

In the v21 of the Support library there is now a solution to this: it's called RoundedBitmapDrawable.

It's basically just like a normal Drawable except you give it a corner radius for the clipping with:

setCornerRadius(float cornerRadius)

So, starting with Bitmap src and a target ImageView, it would look something like this:

RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, src);
dr.setCornerRadius(cornerRadius);
imageView.setImageDrawable(dr);
Jonik
  • 80,077
  • 70
  • 264
  • 372
tyczj
  • 71,600
  • 54
  • 194
  • 296
  • 3
    Great thanks, here's the next step: http://stackoverflow.com/questions/24878740/how-to-use-roundedbitmapdrawable – David d C e Freitas Dec 04 '14 at 09:40
  • actually there is `android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory` so `v4` also supports it. – deadfish Apr 05 '16 at 10:59
  • 2
    @deadfish yes its in `v4` support library but not until `REVISION 21` of the support library – tyczj Apr 06 '16 at 12:44
  • 3
    This is solution is simple and up-to-date. It requires the least amount of code and have great extensibility. Can work with images from local file, cached drawable, or even with Volley's NetworkImageView. I highly agree that this should be the accepted answer nowadays, as @Jonik pointed out. – katie Feb 10 '17 at 16:37
  • 3
    Unfortutately doesn't work with `scaleType` `centerCrop` (support library v25.3.1) – Alex Zaitsev Sep 12 '17 at 08:23
  • you can center crop image view – user158 Jul 10 '19 at 12:43
107

A quick xml solution -

<android.support.v7.widget.CardView
            android:layout_width="40dp"
            android:layout_height="40dp"
            app:cardElevation="0dp"
            app:cardCornerRadius="4dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rounded_user_image"
        android:scaleType="fitXY"/>

</android.support.v7.widget.CardView>

You can set your desired width, height and radius on CardView and scaleType on ImageView.

With AndroidX, use <androidx.cardview.widget.CardView>

Shlok Jhawar
  • 277
  • 2
  • 3
  • 19
Chirag Mittal
  • 1,508
  • 1
  • 12
  • 17
84

I have done by Custom ImageView:

public class RoundRectCornerImageView extends ImageView {

    private float radius = 18.0f;
    private Path path;
    private RectF rect;

    public RoundRectCornerImageView(Context context) {
        super(context);
        init();
    }

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

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

    private void init() {
        path = new Path();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        path.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }
}

How to use:

<com.mypackage.RoundRectCornerImageView
     android:id="@+id/imageView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@drawable/image"
     android:scaleType="fitXY" />

Output:

enter image description here

Hope this would help you.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • this makes image blur – Amit Hooda Dec 16 '16 at 13:34
  • 2
    works even with android:scaleType="centerCrop", simple, doesn't create new bitmap. Thanks! – ernazm Mar 01 '17 at 12:58
  • 2
    @Hiren This solution works fine for ImageView with a background Image. But it doesn't work for ImageViews which has just background color and no Image. Can you please tell me why this happening ? – user2991413 Sep 07 '17 at 09:04
  • `Canvas.clipPath()` may cause `java.lang.UnsupportedOperationException` in some cases. See https://stackoverflow.com/questions/13248904/unsupportedoperationexception-on-clippath – Artyom Jul 02 '18 at 12:38
  • 2
    This solution works only for image set with `android:background`, but not `android:src`. – CoolMind Sep 20 '18 at 10:02
  • Try not to allocate new objects in onDraw() because it bad practice due to perfomance issues rect = new RectF(0, 0, this.getWidth(), this.getHeight()); – Mikhail Valuyskiy Mar 25 '19 at 22:09
  • 1
    i have improved this code [CircularImage](http://fdm.my-style.in/Android/) – S Kumar May 11 '20 at 15:06
  • Perfect ! If anyone needs to round specific corners (not all four). Check this answer : https://stackoverflow.com/questions/41986094/draw-round-corners-on-top-left-top-right-bottom-left-bottom-right-using-path-and – Thomas Pires Oct 10 '21 at 20:14
  • Wow! This actually works on all types of Views not only ImageViews! – Mohamed Salah Feb 12 '22 at 21:14
59

I found that both methods were very helpful in coming up with a working solution. Here is my composite version, that is pixel independent and allows you to have some square corners with the rest of the corners having the same radius (which is the usual use case). With thanks to both of the solutions above:

public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR  ) {

    Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final float densityMultiplier = context.getResources().getDisplayMetrics().density;

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, w, h);
    final RectF rectF = new RectF(rect);

    //make sure that our rounded corner is scaled appropriately
    final float roundPx = pixels*densityMultiplier;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);


    //draw rectangles over the corners we want to be square
    if (squareTL ){
        canvas.drawRect(0, h/2, w/2, h, paint);
    }
    if (squareTR ){
        canvas.drawRect(w/2, h/2, w, h, paint);
    }
    if (squareBL ){
        canvas.drawRect(0, 0, w/2, h/2, paint);
    }
    if (squareBR ){
        canvas.drawRect(w/2, 0, w, h/2, paint);
    }


    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(input, 0,0, paint);

    return output;
}

Also, I overrode ImageView to put this in so I could define it in xml. You may want to add in some of the logic that the super call makes here, but I've commented it as it's not helpful in my case.

    @Override
protected void onDraw(Canvas canvas) {
    //super.onDraw(canvas);
        Drawable drawable = getDrawable();

        Bitmap b =  ((BitmapDrawable)drawable).getBitmap() ;
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();


        Bitmap roundBitmap =  CropImageView.getRoundedCornerBitmap( getContext(), bitmap,10 , w, h , true, false,true, false);
        canvas.drawBitmap(roundBitmap, 0,0 , null);
}

Hope this helps!

TheFlash
  • 5,997
  • 4
  • 41
  • 46
Caspar Harmer
  • 8,097
  • 2
  • 42
  • 39
  • 4
    pretty awesome, especially extending the ImageView – Someone Somewhere Mar 18 '11 at 18:26
  • 2
    A simple way to keep the logic of the ImageView#onDraw() is to set the rounded corner bitmap to the drawable of the ImageView, and leave the super.onDraw() to draw the bitmap. I've created a class [RoundedCornerImageView](http://code.google.com/p/android-batsg/source/browse/android-batsg/src/com/chauhai/android/batsg/widget/RoundedCornerImageView.java), and its example of usage is [here](http://code.google.com/p/android-batsg/wiki/RoundedCornerImageView). Please notice that the getRoundedCornerBitmap() I've used is not pixel independent. – umbalaconmeogia Mar 02 '12 at 15:14
  • Thanks for the RoundedCornerImageView. I used it but modified it to be pixel-density independent. – PacificSky May 24 '12 at 02:34
  • The source code to umba's RoundedCornerImageView is here: http://code.google.com/p/android-batsg/source/browse/trunk/android-batsg/src/com/chauhai/android/batsg/widget/RoundedCornerImageView.java – Someone Somewhere Mar 20 '13 at 22:36
  • @Caspar Harmer working good just 1 edit...there are four conditions..just change them as if I set true,true,false,false it will set bottom corner instead of top corner..otherwise code is working fine.so squareTL and squareTR are condtions for squareBL and squareBR respectively..and vica-versa. – TheFlash Oct 15 '15 at 08:44
  • It gies me NullPointerException at `Bitmap b = ((BitmapDrawable)drawable).getBitmap() ;` inside onDraw. Any solutions? – Geek Guy Jul 16 '18 at 09:12
  • This was answered in 2011... Consider it a legacy answer. – Caspar Harmer Jul 20 '18 at 04:02
50

Rounded image Using ImageLoader here

Create DisplayImageOptions:

DisplayImageOptions options = new DisplayImageOptions.Builder()
    // this will make circle, pass the width of image 
    .displayer(new RoundedBitmapDisplayer(getResources().getDimensionPixelSize(R.dimen.image_dimen_menu))) 
    .cacheOnDisc(true)
    .build();

imageLoader.displayImage(url_for_image,ImageView,options);

Or you can user Picasso Library from Square.

Picasso.with(mContext)
    .load(com.app.utility.Constants.BASE_URL+b.image)
    .placeholder(R.drawable.profile)
    .error(R.drawable.profile)
    .transform(new RoundedTransformation(50, 4))
    .resizeDimen(R.dimen.list_detail_image_size, R.dimen.list_detail_image_size)
    .centerCrop()
    .into(v.im_user);

you can download RoundedTransformation file here here

LaurentY
  • 7,495
  • 3
  • 37
  • 55
shailesh
  • 1,783
  • 2
  • 17
  • 26
  • 3
    The Picasso Library one is good, and very easy to implement, thanks a lot +1 – Hitesh Jan 06 '15 at 12:00
  • 3
    The Picasso library seems to not transform the "placeholder" and "error" image though, so if your image fails to load (error) or takes a while to load initially (placeholder) it won't display the image as a rounded image. https://github.com/square/picasso/issues/337 – Pelpotronic May 01 '15 at 18:14
  • Other useful picasso transformations are provided by this library, which also contains a RoundedCornersTransformation: https://github.com/wasabeef/picasso-transformations – Massimo Jan 25 '17 at 10:45
  • 1
    Doesn't work with cropping images in Univ. Image Loader. – Yar Aug 26 '18 at 11:33
28

As all the answers seemed too complicated for me just for round corners I thought and came to another solution which I think is worth to share, just with XML in case you have some space around the image:

Create a bordered shape with transparent content like this:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners 
        android:radius="30dp" />
    <stroke 
        android:color="#ffffffff"
        android:width="10dp" />
</shape> 

Then in a RelativeLayout you can first place your image and then in the same location above the shape with another ImageView. The cover-shape should be larger in size by the amount of the border width. Be careful to take a larger corner radius as the outer radius is defined but the inner radius is what covers your image.

Hope it helps somebody, too.

Edit as per CQM request the relative layout example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageToShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imgCorners"
        android:layout_alignLeft="@+id/imgCorners"
        android:layout_alignRight="@+id/imgCorners"
        android:layout_alignTop="@+id/imgCorners"
        android:background="#ffffff"
        android:contentDescription="@string/desc"
        android:padding="5dp"
        android:scaleType="centerCrop" />

    <ImageView
        android:id="@+id/imgCorners"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/desc"
        android:src="@drawable/corners_white" />

</RelativeLayout>
Christian
  • 4,596
  • 1
  • 26
  • 33
  • can you elaborate more on this with more code, especially what is being done with the second image view and where the "bordered shape" xml is being applied (as src or as background?) several questions here. I want to like this solution since it will let me control all four corners independently – CQM Feb 27 '14 at 16:41
  • 1
    Although seems to be a simple answer, it unfortunately adds margin around the "masked" image view which is undesirable side effect. – Abdalrahman Shatou May 11 '14 at 23:53
  • yes, but the same works with an ImageView based on a PNG-Drawable with rounded corners and transparent background or a 9-Patch-Drawable if you have an undefined aspect. – Christian May 12 '14 at 06:53
  • I am doing the same way, and its working; just willing to know if it will not create any problem with orientation and different phone size? – Language Lassi Oct 09 '14 at 14:50
  • If you keep the dimensions relative to eachother this should not create a problem. – Christian Oct 10 '14 at 20:51
  • where can i set the image in above case? means how will change the image? – Shirish Herwade Jan 28 '15 at 10:41
  • the image is the `@+id/imageToShow` you can change the src-Tag in XML or modify it programmatically with `findViewById` – Christian Jan 29 '15 at 01:10
23

It can be done with a ShapeableImageView using a ShapeAppearanceOverlay:

<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/avatar"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:padding="4dp"
    app:shapeAppearance="@style/ShapeAppearanceOverlay.Avatar"/>

Where style ShapeAppearanceOverlay.Avatar resides in res/values/styles.xml:

<style name="ShapeAppearanceOverlay.Avatar" parent="ShapeAppearance.MaterialComponents.SmallComponent">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

This just need equal layout_height and layout_width set, else with will be a pill an no circle.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
14

As of recently, there is another way - using Glide's Generated API. It takes some initial work but then gives you all the power of Glide with the flexibility to do anything because you writhe the actual code so I think it's a good solution for the long run. Plus, the usage is very simple and neat.

First, setup Glide version 4+:

implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'

Then create Glid's app module class to trigger the annotation processing:

@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}

Then create the Glide extension which actually does the work. You can customize it to do whatever you want:

@GlideExtension
public class MyGlideExtension {

    private MyGlideExtension() {}

    @NonNull
    @GlideOption
    public static RequestOptions roundedCorners(RequestOptions options, @NonNull Context context, int cornerRadius) {
        int px = Math.round(cornerRadius * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return options.transforms(new RoundedCorners(px));
    }
}

After adding these files, build your project.

Then use it in your code like this:

GlideApp.with(this)
        .load(imageUrl)
        .roundedCorners(getApplicationContext(), 5)
        .into(imageView);
CoolMind
  • 26,736
  • 15
  • 188
  • 224
Sir Codesalot
  • 7,045
  • 2
  • 50
  • 56
  • .roundedCorners not coming do we need to setup anything else? Even after rebuilding project – Cyph3rCod3r Dec 18 '18 at 10:33
  • This worked for me, thank you. I found it simpler to avoid using the `@GlideExtension` annotated class and just went with `.transform(new RoundedCorners(px))` where `px` is the same (`int px = Math.round(cornerRadius * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));`). – Michael Osofsky Aug 12 '19 at 21:01
14

My implementation of ImageView with rounded corners widget, that (down||up)sizes image to required dimensions. It utilizes code form CaspNZ.

public class ImageViewRounded extends ImageView {

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {
        BitmapDrawable drawable = (BitmapDrawable) getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return; 
        }

        Bitmap fullSizeBitmap = drawable.getBitmap();

        int scaledWidth = getMeasuredWidth();
        int scaledHeight = getMeasuredHeight();

        Bitmap mScaledBitmap;
        if (scaledWidth == fullSizeBitmap.getWidth() && scaledHeight == fullSizeBitmap.getHeight()) {
            mScaledBitmap = fullSizeBitmap;
        } else {
            mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */);
        }

        Bitmap roundBitmap = ImageUtilities.getRoundedCornerBitmap(getContext(), mScaledBitmap, 5, scaledWidth, scaledHeight,
                false, false, false, false);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

}
Flexo
  • 87,323
  • 22
  • 191
  • 272
Damjan
  • 2,933
  • 1
  • 19
  • 10
13

There is a cool library that allows you to shape imageviews.

Here is an example:

<com.github.siyamed.shapeimageview.mask.PorterShapeImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:siShape="@drawable/shape_rounded_rectangle"
    android:src="@drawable/neo"
    app:siSquare="true"/>

Shape definition:

<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <corners
        android:topLeftRadius="18dp"
        android:topRightRadius="18dp"
        android:bottomLeftRadius="18dp"
        android:bottomRightRadius="18dp" />
    <solid android:color="@color/black" />
</shape>

Result:

result

grrigore
  • 1,050
  • 1
  • 21
  • 39
12

Try the Material Components Library and use the ShapeableImageView.
Somethig like this :

Java :

imageView=new ShapeableImageView(context);
imageView.setShapeAppearanceModel(
        imageView.getShapeAppearanceModel()
                 .toBuilder()
                 .setAllCornerSizes(20)
                 .build());

Kotlin :

val imageView = ShapeableImageView(context)
imageView.setShapeAppearanceModel(
        imageView.getShapeAppearanceModel()
                 .toBuilder()
                 .setAllCornerSizes(20f)
                 .build())

enter image description here

ucMedia
  • 4,105
  • 4
  • 38
  • 46
10

Here is a simple example overriding imageView, you can then also use it in layout designer to preview.

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 defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        float radius = 0.1f;
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        RoundedBitmapDrawable rid = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
        rid.setCornerRadius(bitmap.getWidth() * radius);
        super.setImageDrawable(rid);
    }
}

This is for fast solution. Radius is used on all corners and is based of percentage of bitmap width.

I just overrided setImageDrawable and used support v4 method for rounded bitmap drawable.

Usage:

<com.example.widgets.RoundedImageView
        android:layout_width="39dp"
        android:layout_height="39dp"
        android:src="@drawable/your_drawable" />

Preview with imageView and custom imageView:

enter image description here

Badr At
  • 658
  • 7
  • 22
deadfish
  • 11,996
  • 12
  • 87
  • 136
9

Kotlin

import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import kotlinx.android.synthetic.main.activity_main.*

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.myImage)
val rounded = RoundedBitmapDrawableFactory.create(resources, bitmap)
rounded.cornerRadius = 20f
profileImageView.setImageDrawable(rounded)

To make ImageView Circular we can change cornerRadius with:

rounded.isCircular = true
Vahid
  • 3,352
  • 2
  • 34
  • 42
8

Apply a shape to your imageView as below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#faf5e6" />
    <stroke
        android:width="1dp"
        android:color="#808080" />
    <corners android:radius="15dp" />
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
</shape>

it may be helpful to you friend.

Trikaldarshiii
  • 11,174
  • 16
  • 67
  • 95
jigar
  • 1,571
  • 6
  • 23
  • 46
7

Why not do clipping in draw()?

Here is my solution:

  • Extend RelativeLayout with clipping
  • Put ImageView (or other views) into the layout:

Code:

public class RoundRelativeLayout extends RelativeLayout {

    private final float radius;

    public RoundRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray attrArray = context.obtainStyledAttributes(attrs,
                R.styleable.RoundRelativeLayout);
        radius = attrArray.getDimension(
                R.styleable.RoundRelativeLayout_radius, 0);
    }

    private boolean isPathValid;
    private final Path path = new Path();

    private Path getRoundRectPath() {
        if (isPathValid) {
            return path;
        }

        path.reset();

        int width = getWidth();
        int height = getHeight();
        RectF bounds = new RectF(0, 0, width, height);

        path.addRoundRect(bounds, radius, radius, Direction.CCW);
        isPathValid = true;
        return path;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.clipPath(getRoundRectPath());
        super.dispatchDraw(canvas);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.clipPath(getRoundRectPath());
        super.draw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int oldWidth = getMeasuredWidth();
        int oldHeight = getMeasuredHeight();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int newWidth = getMeasuredWidth();
        int newHeight = getMeasuredHeight();
        if (newWidth != oldWidth || newHeight != oldHeight) {
            isPathValid = false;
        }
    }

}
Max Base
  • 639
  • 1
  • 7
  • 15
fishautumn
  • 364
  • 3
  • 6
7

Romain Guy is where it's at.

Minified version as follows.

Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.image)).getBitmap();

Bitmap bitmapRounded = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(bitmapRounded);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0.0f, 0.0f, bitmap.getWidth(), bitmap.getHeight())), 10, 10, paint);

imageView.setImageBitmap(bitmapRounded);
Alex
  • 5,909
  • 2
  • 35
  • 25
  • sadly, even though it works, but just like the rest of the solutions here, it creates a new bitmap instead of using the current one. – android developer May 01 '13 at 09:22
  • not really. bitmapRounded would be used again and again. if you had access to the drawable canvas, you can use the draw method directly instead of generating a new bitmap. – Alex May 01 '13 at 13:43
  • how do you do that? suppose i don't use any special drawable and only handle a single bitmap and use setImageBitmap in the end of the process. how would i achieve such a thing? – android developer May 01 '13 at 13:52
  • check out romain guy's example http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/ and sample application https://docs.google.com/file/d/0B3dxhm5xm1sia2NfM3VKTXNjUnc/edit – Alex May 01 '13 at 13:55
  • both don't change the bitmap , but wrap it using a custom drawable and a custom imageview. this isn't what i asked about. i asked how do you change the bitmap itself. – android developer May 01 '13 at 14:09
  • sorry for the confusion. what are you trying to do? if what you want to do is round corners, you can't really just modify the bitmap in place. basically, this method creates a rounded rectangle, and draws the original bitmap inside it (like a sort of background). somewhat similar to the concept of blitting and sprites. the romain example demonstrates using an existing canvas to draw on, instead of creating a second bitmap, which can be more efficient. my demo basically draws the bitmap twice, once to draw the rounded bitmap itself, once again to draw the image view. – Alex May 06 '13 at 20:40
  • Can you please share the whole sample of yours? Also, why isn't it possible to modify a bitmap? it is possible, as bitmaps can be mutable . – android developer May 06 '13 at 21:30
  • That is the whole sample. Romain guy has a related sample, link above. It may be possible to modify the bitmap in place, but I'm not sure how to do it with built-in libraries. For instance, somehow cutting off the corners of an existing bitmap, thereby making the corners transparent, rounded, and anti-aliased. You would have to draw a rounded rectangle, and then subtracting the outside. Also, even if is possible, it may not be more efficient to do so. Blitting is a very common technique. – Alex May 07 '13 at 12:53
  • is the correct math formula for rounded corners is: (x-center_x)^2 + (y - center_y)^2 < radius^2 ? this means that each point that is within this location should be transparent, for each of the corners? or maybe there is a better way than doing some math magic? btw, romain guy has a serious OOM bug in his sample (try rotating the device multiple times and see it) and you need to have the bitmap at the exact size for the imageView or else it smears. – android developer May 07 '13 at 19:20
  • @user4o01 i've found a rounded-corner-imageview library that was very problematic at first, but now it's fine and works well. i think this is the library website: https://github.com/vinc3m1/RoundedImageView . however, i've tried adding some more effects to it without much luck so i've posted a question about it here: http://stackoverflow.com/questions/16383842/how-to-add-an-outer-shadow-for-a-rounded-corners-drawable – android developer Dec 21 '13 at 14:51
  • How about if I want to round only some corners of the image but not all? – CQM Feb 27 '14 at 16:16
7

You should extend ImageView and draw your own rounded rectangle.

If you want a frame around the image you could also superimpose the rounded frame on top of the image view in the layout.

[edit]Superimpose the frame on to op the original image, by using a FrameLayout for example. The first element of the FrameLayout will be the image you want to diplay rounded. Then add another ImageView with the frame. The second ImageView will be displayed on top of the original ImageView and thus Android will draw it's contents above the orignal ImageView.

MrSnowflake
  • 4,724
  • 3
  • 29
  • 32
  • Thank you. But there is only setDrawable method for ImageView, how can I setDrawable of the ImageView to the content of my image and then superimpose a rounded frame on top of the ImageView? – michael Mar 17 '10 at 20:45
  • I'm sorry, I was being unclear. I meant superimposing in the layout: thus (ie) use a `FrameLayout` put an `ImageView` in it and add another `ImageView` with the rounded frame. That way the first `ImageView` will display your selected picture and the second `ImageFrame` will display the rounded frame. – MrSnowflake Mar 19 '10 at 10:27
  • Correct - with FrameLayout you can overlay one image/view with another. You can also make use of the android:foreground tag of FrameLayout. – Richard Le Mesurier Nov 29 '11 at 14:10
7

This pure xml solution was good enough in my case. http://www.techrepublic.com/article/pro-tip-round-corners-on-an-android-imageview-with-this-hack/

EDIT

Here's the answer in a nutshell:

In the /res/drawable folder, create a frame.xml file. In it, we define a simple rectangle with rounded corners and a transparent center.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="#00ffffff" />
     <padding android:left="6dp"
        android:top="6dp"
        android:right="6dp"
        android:bottom="6dp" />
     <corners android:radius="12dp" />
     <stroke android:width="6dp" android:color="#ffffffff" />
</shape>

In your layout file you add a LinearLayout that contains a standard ImageView, as well as a nested FrameLayout. The FrameLayout uses padding and the custom drawable to give the illusion of rounded corners.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center" 
    android:background="#ffffffff">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="6dp"
        android:src="@drawable/tr"/>

    <FrameLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="6dp"
            android:src="@drawable/tr"/>

        <ImageView 
             android:src="@drawable/frame"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />

    </FrameLayout>

</LinearLayout>
Max Base
  • 639
  • 1
  • 7
  • 15
j7nn7k
  • 17,995
  • 19
  • 78
  • 88
7

Props to George Walters II above, I just took his answer and extended it a bit to support rounding individual corners differently. This could be optimized a bit further (some of the target rects overlap), but not a whole lot.

I know this thread is a bit old, but its one of the top results for queries on Google for how to round corners of ImageViews on Android.

/**
 * Use this method to scale a bitmap and give it specific rounded corners.
 * @param context Context object used to ascertain display density.
 * @param bitmap The original bitmap that will be scaled and have rounded corners applied to it.
 * @param upperLeft Corner radius for upper left.
 * @param upperRight Corner radius for upper right.
 * @param lowerRight Corner radius for lower right.
 * @param lowerLeft Corner radius for lower left.
 * @param endWidth Width to which to scale original bitmap.
 * @param endHeight Height to which to scale original bitmap.
 * @return Scaled bitmap with rounded corners.
 */
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap bitmap, float upperLeft,
        float upperRight, float lowerRight, float lowerLeft, int endWidth,
        int endHeight) {
    float densityMultiplier = context.getResources().getDisplayMetrics().density;

    // scale incoming bitmap to appropriate px size given arguments and display dpi
    bitmap = Bitmap.createScaledBitmap(bitmap, 
            Math.round(endWidth * densityMultiplier),
            Math.round(endHeight * densityMultiplier), true);

    // create empty bitmap for drawing
    Bitmap output = Bitmap.createBitmap(
            Math.round(endWidth * densityMultiplier),
            Math.round(endHeight * densityMultiplier), Config.ARGB_8888);

    // get canvas for empty bitmap
    Canvas canvas = new Canvas(output);
    int width = canvas.getWidth();
    int height = canvas.getHeight();

    // scale the rounded corners appropriately given dpi
    upperLeft *= densityMultiplier;
    upperRight *= densityMultiplier;
    lowerRight *= densityMultiplier;
    lowerLeft *= densityMultiplier;

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.WHITE);

    // fill the canvas with transparency
    canvas.drawARGB(0, 0, 0, 0);

    // draw the rounded corners around the image rect. clockwise, starting in upper left.
    canvas.drawCircle(upperLeft, upperLeft, upperLeft, paint);
    canvas.drawCircle(width - upperRight, upperRight, upperRight, paint);
    canvas.drawCircle(width - lowerRight, height - lowerRight, lowerRight, paint);
    canvas.drawCircle(lowerLeft, height - lowerLeft, lowerLeft, paint);

    // fill in all the gaps between circles. clockwise, starting at top.
    RectF rectT = new RectF(upperLeft, 0, width - upperRight, height / 2);
    RectF rectR = new RectF(width / 2, upperRight, width, height - lowerRight);
    RectF rectB = new RectF(lowerLeft, height / 2, width - lowerRight, height);
    RectF rectL = new RectF(0, upperLeft, width / 2, height - lowerLeft);

    canvas.drawRect(rectT, paint);
    canvas.drawRect(rectR, paint);
    canvas.drawRect(rectB, paint);
    canvas.drawRect(rectL, paint);

    // set up the rect for the image
    Rect imageRect = new Rect(0, 0, width, height);

    // set up paint object such that it only paints on Color.WHITE
    paint.setXfermode(new AvoidXfermode(Color.WHITE, 255, AvoidXfermode.Mode.TARGET));

    // draw resized bitmap onto imageRect in canvas, using paint as configured above
    canvas.drawBitmap(bitmap, imageRect, imageRect, paint);

    return output;
}
sorrodos
  • 79
  • 1
  • 1
  • +1 for adding in the density multiplier and adding support for individually rounding corners. I actually used the solution at the top, as your solution didn't quite work - but it was very helpful! See my composite solution below: – Caspar Harmer Mar 09 '11 at 21:44
7

None of the methods provided in the answers worked for me. I found the following way works if your android version is 5.0 or above:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

    ViewOutlineProvider provider = new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            int curveRadius = 24;
            outline.setRoundRect(0, 0, view.getWidth(), (view.getHeight()+curveRadius), curveRadius);
        }
    };
    imageview.setOutlineProvider(provider);
    imageview.setClipToOutline(true);
}

No xml shapes to be defined, and the code above create corners only for top, which normal methods won't work. If you need 4 corners to be rounded, remove:

"+ curveRadius"  

From the parameter for bottom in setRoundRect. You can further expand the shape to any others by specifying outlines that suit your needs. Check out the following link:

Android Developer Documentation.


Note, as with any measure in Android, you have to "convert" the size typically from DP. In the example above, say you want the radius to be 24

                            int curveRadius = 24;

For example you may be later adding a border in a drawable with the radius set as "24" and you wish it to match. Hence,

    float desiredRadius = 24;
    float radiusConverted = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            desiredRadius,
            itemView.getContext().getResources().getDisplayMetrics());

and then

                            int curveRadius = radiusConverted;
Fattie
  • 27,874
  • 70
  • 431
  • 719
us_david
  • 4,431
  • 35
  • 29
  • AHHHHH .. multiply by the screen density ! – Fattie Mar 22 '21 at 15:46
  • dear @us_david , regarding your amazing answer, I added a note about getting the radius correct to match other radius in the app. obviously delete or edit as you seer fit! thank you so much for the answer !!! – Fattie Mar 22 '21 at 16:06
5

If you are using Glide Library this would be helpful:

Glide.with(getApplicationContext())
     .load(image_url)
     .asBitmap()
     .centerCrop()
     .into(new BitmapImageViewTarget(imageView) {
        @Override
        protected void setResource(Bitmap resource) {
          RoundedBitmapDrawable circularBitmapDrawable =
                       RoundedBitmapDrawableFactory.create(getApplicationContext().getResources(), resource);
          circularBitmapDrawable.setCornerRadius(dpToPx(10));
          circularBitmapDrawable.setAntiAlias(true);
          imageView.setImageDrawable(circularBitmapDrawable);
        }
     });


public int dpToPx(int dp) {
  DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
  return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Anirudh
  • 2,767
  • 5
  • 69
  • 119
  • If using Glide version 4 and above use --- RequestOptions requestOptions = new RequestOptions(); requestOptions = requestOptions.transforms(new CenterCrop(), new RoundedCorners(16)); Glide.with(itemView.getContext()) .load(item.getImage()) .apply(requestOptions) .into(mProgramThumbnail); – B.shruti Apr 19 '18 at 09:42
  • @B.shruti, probably it doesn't work. See more fresh solutions. – CoolMind Dec 15 '20 at 21:09
  • Anirudh, wow, it works for rectangular images! I converted to Kotlin, and it works for Glide 4. In this case `.asBitmap()` should be inserted before `.load(image_url)`. – CoolMind Dec 15 '20 at 21:15
5

The following creates a rounded rectangle layout object that draws a rounded rectangle around any child objects that are placed in it. It also demonstrates how to create views and layouts programmatically without using the layout xml files.

package android.example;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MessageScreen extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  int mainBackgroundColor = Color.parseColor("#2E8B57");
  int labelTextColor = Color.parseColor("#FF4500");
  int messageBackgroundColor = Color.parseColor("#3300FF");
  int messageTextColor = Color.parseColor("#FFFF00");

  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int minMarginSize = Math.round(density * 8);
  int paddingSize = minMarginSize * 2;
  int maxMarginSize = minMarginSize * 4;

  TextView label = new TextView(this);
  /*
   * The LayoutParams are instructions to the Layout that will contain the
   * View for laying out the View, so you need to use the LayoutParams of
   * the Layout that will contain the View.
   */
  LinearLayout.LayoutParams labelLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  label.setLayoutParams(labelLayoutParams);
  label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
  label.setPadding(paddingSize, paddingSize, paddingSize, paddingSize);
  label.setText(R.string.title);
  label.setTextColor(labelTextColor);

  TextView message = new TextView(this);
  RoundedRectangle.LayoutParams messageLayoutParams = new RoundedRectangle.LayoutParams(
 LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to put some extra space around the
   * View.
   */
  messageLayoutParams.setMargins(minMarginSize, paddingSize,
    minMarginSize, maxMarginSize);
  message.setLayoutParams(messageLayoutParams);
  message.setTextSize(TypedValue.COMPLEX_UNIT_SP, paddingSize);
  message.setText(R.string.message);
  message.setTextColor(messageTextColor);
  message.setBackgroundColor(messageBackgroundColor);

  RoundedRectangle messageContainer = new RoundedRectangle(this);
  LinearLayout.LayoutParams messageContainerLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  messageContainerLayoutParams.setMargins(paddingSize, 0, paddingSize, 0);
  messageContainer.setLayoutParams(messageContainerLayoutParams);
  messageContainer.setOrientation(LinearLayout.VERTICAL);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This tells the RoundedRectangle to color the the exta space that was
   * put around the View as well as the View. This is exterior color of
   * the RoundedRectangle.
   */
  messageContainer.setBackgroundColor(mainBackgroundColor);
  /*
   * This is one of the calls must made to force a ViewGroup to call its
   * draw method instead of just calling the draw method of its children.
   * This is the interior color of the RoundedRectangle. It must be
   * different than the exterior color of the RoundedRectangle or the
   * RoundedRectangle will not call its draw method.
   */
  messageContainer.setInteriorColor(messageBackgroundColor);
  // Add the message to the RoundedRectangle.
  messageContainer.addView(message);

  //
  LinearLayout main = new LinearLayout(this);
  LinearLayout.LayoutParams mainLayoutParams = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  main.setLayoutParams(mainLayoutParams);
  main.setOrientation(LinearLayout.VERTICAL);
  main.setBackgroundColor(mainBackgroundColor);
  main.addView(label);
  main.addView(messageContainer);

  setContentView(main);
 }
}

The class for RoundedRectangle layout object is as defined here:

/**
 *  A LinearLayout that draws a rounded rectangle around the child View that was added to it.
 */
package android.example;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;

/**
 * A LinearLayout that has rounded corners instead of square corners.
 * 
 * @author Danny Remington
 * 
 * @see LinearLayout
 * 
 */
public class RoundedRectangle extends LinearLayout {
 private int mInteriorColor;

 public RoundedRectangle(Context p_context) {
  super(p_context);
 }

 public RoundedRectangle(Context p_context, AttributeSet attributeSet) {
  super(p_context, attributeSet);
 }

 // Listener for the onDraw event that occurs when the Layout is drawn.
 protected void onDraw(Canvas canvas) {
  Rect rect = new Rect(0, 0, getWidth(), getHeight());
  RectF rectF = new RectF(rect);
  DisplayMetrics metrics = new DisplayMetrics();
  Activity activity = (Activity) getContext();
  activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float density = metrics.density;
  int arcSize = Math.round(density * 10);

  Paint paint = new Paint();
  paint.setColor(mInteriorColor);

  canvas.drawRoundRect(rectF, arcSize, arcSize, paint);
 }

 /**
  * Set the background color to use inside the RoundedRectangle.
  * 
  * @param Primitive int - The color inside the rounded rectangle.
  */
 public void setInteriorColor(int interiorColor) {
  mInteriorColor = interiorColor;
 }

 /**
  * Get the background color used inside the RoundedRectangle.
  * 
  * @return Primitive int - The color inside the rounded rectangle.
  */
 public int getInteriorColor() {
  return mInteriorColor;
 }

}
Danny Remington - OMS
  • 5,244
  • 4
  • 32
  • 21
4

Thanks a lot to first answer. Here is modified version to convert a rectangular image into a square one (and rounded) and fill color is being passed as parameter.

public static Bitmap getRoundedBitmap(Bitmap bitmap, int pixels, int color) {

    Bitmap inpBitmap = bitmap;
    int width = 0;
    int height = 0;
    width = inpBitmap.getWidth();
    height = inpBitmap.getHeight();

    if (width <= height) {
        height = width;
    } else {
        width = height;
    }

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

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, width, height);
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(inpBitmap, rect, rect, paint);

    return output;
}
mkm
  • 89
  • 3
4

if your image is on internet the best way is using glide and RoundedBitmapDrawableFactory (from API 21 - but available in support library) like so:

 Glide.with(ctx).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
    @Override
    protected void setResource(Bitmap res) {
        RoundedBitmapDrawable bitmapDrawable =
             RoundedBitmapDrawableFactory.create(ctx.getResources(), res);
        bitmapDrawable.setCircular(true);//comment this line and uncomment the next line if you dont want it fully cricular
        //circularBitmapDrawable.setCornerRadius(cornerRadius);
        imageView.setImageDrawable(bitmapDrawable);
    }
});
Amir Ziarati
  • 14,248
  • 11
  • 47
  • 52
  • This is an elegant api, however, .centerInside seems to be missing, hence it is perhaps better to use xml to define such parameters – carl Dec 02 '16 at 07:03
  • This is also useful when image is in resources and you need to use `centerCrop` – Artyom Jul 02 '18 at 12:55
3

Answer for the question that is redirected here: "How to create a circular ImageView in Android?"

public static Bitmap getRoundBitmap(Bitmap bitmap) {

    int min = Math.min(bitmap.getWidth(), bitmap.getHeight());

    Bitmap bitmapRounded = Bitmap.createBitmap(min, min, bitmap.getConfig());

    Canvas canvas = new Canvas(bitmapRounded);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min/2, min/2, paint);

    return bitmapRounded;
}
Andrew
  • 36,676
  • 11
  • 141
  • 113
3

you can use only ImageView in your layout and using glide, you can apply round corners using this method.

first in your gradle write,

compile 'com.github.bumptech.glide:glide:3.7.0'

for image with rounded corners,

public void loadImageWithCorners(String url, ImageView view) {
    Glide.with(context)
            .load(url)
            .asBitmap()
            .centerCrop()
            .placeholder(R.color.gray)
            .error(R.color.gray)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .into(new BitmapImageViewTarget(view) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                    circularBitmapDrawable.setCornerRadius(32.0f); // radius for corners
                    view.setImageDrawable(circularBitmapDrawable);
                }
            });
}

call method :

loadImageWithCorners("your url","your imageview");
Deep Patel
  • 2,584
  • 2
  • 15
  • 28
3

By using below code you can change top corner radius

val image = findViewById<ImageView>(R.id.image)
val curveRadius = 20F

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

    image.outlineProvider = object : ViewOutlineProvider() {

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun getOutline(view: View?, outline: Outline?) {
            outline?.setRoundRect(0, 0, view!!.width, (view.height+curveRadius).toInt(), curveRadius)
        }
    }

    image.clipToOutline = true

}
Max Base
  • 639
  • 1
  • 7
  • 15
P A Gosai
  • 553
  • 5
  • 22
  • For android it would be like this: float curveRadius = 20F; ViewOutlineProvider outlineProvider = new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(0, 0, view.getWidth(), (int) (view.getHeight()+curveRadius), curveRadius); } }; imatge.setOutlineProvider(outlineProvider); imatge.setClipToOutline(true); – OneKe Apr 05 '22 at 20:09
2

With the help of glide library and RoundedBitmapDrawableFactory class it's easy to achieve. You may need to create circular placeholder image.

    Glide.with(context)
        .load(imgUrl)
        .asBitmap()
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.placeholder)
        .into(new BitmapImageViewTarget(imgProfilePicture) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(),
                        Bitmap.createScaledBitmap(resource, 50, 50, false));
                drawable.setCornerRadius(10); //drawable.setCircular(true);
                imgProfilePicture.setImageDrawable(drawable);
            }
        });
Chitrang
  • 5,097
  • 1
  • 35
  • 58
2

For the ones that are using Glide and Kotlin, you can achieve so by extending RequestBuilder

fun <T> GlideRequest<T>.roundCorners(cornerRadius: Int) =
    apply(RequestOptions().transform(RoundedCorners(cornerRadius)))

and use as;

 GlideApp.with(context)
            .load(url)
            .roundCorners(context.resources.getDimension(R.dimen.radius_in_dp).toInt())
            .into(imgView)
dgngulcan
  • 3,101
  • 1
  • 24
  • 26
2

for rounded border use below code

  <com.google.android.material.card.MaterialCardView
                        android:id="@+id/circle"
                        android:layout_width="45dp"
                        android:layout_height="45dp"
                        android:layout_marginStart="5dp"

                        app:cardCornerRadius="25dp"
                        app:strokeColor="@color/colorDarkGreen"

                        app:strokeWidth="1dp">

                        <ImageView
                            android:id="@+id/toolbarProfile"
                            android:scaleType="fitXY"

                            android:layout_width="match_parent"
                            android:layout_height="match_parent"

                            android:src="@drawable/avater" />
                    </com.google.android.material.card.MaterialCardView>
Shiba Das
  • 350
  • 4
  • 12
1

Quite a lot of answers!

I followed this example which a few people have kinda suggested too: http://www.techrepublic.com/article/pro-tip-round-corners-on-an-android-imageview-with-this-hack/

However, what I needed was a coloured circle, behind a transparent image. For anyone who is interested in doing the same...

1) Set the FrameLayout to the width and height - in my case the size of the image (50dp).
2) Place the ImageView that has the src = "@drawable/...", above the ImageView that has the image. Give it an id, in my case I called it iconShape
3) Drawable mask.xml should have a solid colour of #ffffffff 4) If you want to dynamically change the circle colour in your code, do

ImageView iv2 = (ImageView) v.findViewById(R.id.iconShape);
Drawable shape = getResources().getDrawable(R.drawable.mask);
shape.setColorFilter(Color.BLUE, Mode.MULTIPLY);
iv2.setImageDrawable(shape);
rharvey
  • 1,987
  • 1
  • 28
  • 23
  • That example was the only one which worked for me because I'm using a rounded border (stroke)... So, the image must not only be cropped properly but it should respect the rounded edges. Using other samples, the image respect the padding.. but even then, the image overlap the border (stroke) in the edges – guipivoto Aug 03 '18 at 13:13
1

You can try this library - RoundedImageView

It is:

A fast ImageView that supports rounded corners, ovals, and circles. A full superset of CircleImageView.

I've used it in my project, and it is very easy.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
1

Use this to get circular image with border-

    public static Bitmap getCircularBitmapWithBorder(Bitmap bitmap, int bordercolor) {
    if (bitmap == null || bitmap.isRecycled()) {
        return null;
    }
    int borderWidth=(int)(bitmap.getWidth()/40);
    final int width = bitmap.getWidth() + borderWidth;
    final int height = bitmap.getHeight() + borderWidth;

    Bitmap canvasBitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP,
            TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);

    Canvas canvas = new Canvas(canvasBitmap);
    float radius = width > height ? ((float) height) / 2f
            : ((float) width) / 2f;
    canvas.drawCircle(width / 2, height / 2, radius, paint);
    paint.setShader(null);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(bordercolor);
    paint.setStrokeWidth(borderWidth);
    canvas.drawCircle(width / 2, height / 2, radius - borderWidth / 2,
            paint);
    return canvasBitmap;
}
Jim Lu
  • 3
  • 1
  • 4
Akshay Paliwal
  • 3,718
  • 2
  • 39
  • 43
1

I'm using a custom view that I layout on top of the other ones and that just draws the 4 small inverted corners in the same color as the background.

Advantages:

  • Does not allocate a bitmap.
  • Works whatever the View you want to apply the rounded corners.
  • Works for all API levels ;)

Code:

public class RoundedCornersView extends View {
    private float mRadius;
    private int mColor = Color.WHITE;
    private Paint mPaint;
    private Path mPath;

    public RoundedCornersView(Context context) {
        super(context);
        init();
    }

    public RoundedCornersView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.RoundedCornersView,
                0, 0);

        try {
            setRadius(a.getDimension(R.styleable.RoundedCornersView_radius, 0));
            setColor(a.getColor(R.styleable.RoundedCornersView_cornersColor, Color.WHITE));
        } finally {
            a.recycle();
        }
    }

    private void init() {
        setColor(mColor);
        setRadius(mRadius);
    }

    private void setColor(int color) {
        mColor = color;
        mPaint = new Paint();
        mPaint.setColor(mColor);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);

        invalidate();
    }

    private void setRadius(float radius) {
        mRadius = radius;
        RectF r = new RectF(0, 0, 2 * mRadius, 2 * mRadius);
        mPath = new Path();
        mPath.moveTo(0,0);
        mPath.lineTo(0, mRadius);
        mPath.arcTo(r, 180, 90);
        mPath.lineTo(0,0);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        /*This just draws 4 little inverted corners */

        int w = getWidth();
        int h = getHeight();
        canvas.drawPath(mPath, mPaint);
        canvas.save();
        canvas.translate(w, 0);
        canvas.rotate(90);
        canvas.drawPath(mPath, mPaint);
        canvas.restore();
        canvas.save();
        canvas.translate(w, h);
        canvas.rotate(180);
        canvas.drawPath(mPath, mPaint);
        canvas.restore();
        canvas.translate(0, h);
        canvas.rotate(270);
        canvas.drawPath(mPath, mPaint);
    }
}
mbonnin
  • 6,893
  • 3
  • 39
  • 55
1

Thanks to melanke you can use a custom classand create a custom circular ImageView.

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;

public class MLRoundedImageView extends android.support.v7.widget.AppCompatImageView {

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

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

    public MLRoundedImageView(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(), 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 int color = 0xffa19774;
        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("#BAB399"));
        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;
    }

}

And then use it in XML like:

<your.package.name.MLRoundedImageView
..
/>

Source

Ghasem
  • 14,455
  • 21
  • 138
  • 171
1

For Glide 4.x.x

use this simple code

Glide
  .with(context)
  .load(uri)
  .apply(
      RequestOptions()
        .circleCrop())
  .into(imageView)
Basi
  • 3,009
  • 23
  • 28
1

you can use roundedImageView Library very easy:

compile 'com.makeramen:roundedimageview:2.3.0'

and then:

<com.makeramen.roundedimageview.RoundedImageView
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:id="@+id/img_episode"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:elevation="7dp"
  app:riv_border_color="@color/colorPrimary"
  app:riv_border_width="1dip"
  app:riv_corner_radius="10dip"
  app:riv_mutate_background="true"
  />
Milad Mohamadi
  • 127
  • 1
  • 10
1

Easiest solution I think is something like this :-

Step 1 - Create a shape drawable file as below :-

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@color/white" />

    <corners android:radius="@dimen/dimen_10dp" />

    <stroke
        android:width="1dp"
        android:color="@color/white" />
</shape>

Step 2 - Use above drawable in code.

Drawable drawable = ContextCompat.getDrawable(mActivity, R.drawable.photos_round_shape);
            drawable.mutate().setColorFilter(randomColor, PorterDuff.Mode.SRC_ATOP);
            imageView.setBackground(drawable);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
               imageView.setClipToOutline(true);
            }

Glide.with(mContext)
                .setDefaultRequestOptions(getNoAnimationOptions())
                .load(url)
                .into(imageView);

Hope this helps.

Jemshit
  • 9,501
  • 5
  • 69
  • 106
1

I suggest using the Coil library for this scenario

Coil is Kotlin-first and uses modern libraries including Coroutines, OkHttp, Okio, and AndroidX Lifecycles.

github link

Javid Sattar
  • 749
  • 8
  • 14
1

***The question is old, I know, but here's another simpler way of rounding an image:

This is a programmatic method.

Create your void and ...

} public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.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());
final RectF rectF = new RectF(rect);
final float roundPx = pixels; paint.setAntiAlias(true); 
canvas.drawARGB(0, 0, 0, 0); paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint); return output;

Load your image, then set the rounded corners

imageview1.setImageResource(R.drawable.yourimage);

Bitmap bm = ((android.graphics.drawable.BitmapDrawable) imageview1.getDrawable()).getBitmap();
imageview1.setImageBitmap(getRoundedCornerBitmap(bm, 30)); 

With 30 being your radius and you'll get something like this:

example of a rounded image/icon

Nevermind the way my image looks, it's a zoomed small icon

0

This isn't exactly the answer, but it's a solution that is similar. It may help people who were in the same boat as I was.

My image, an application logo, had a transparent background, and I was applying an XML gradient as the image background. I added the necessary padding/margins to the imageView in XML, then added this as my background:

<?xml version="1.0" encoding="utf-8"?>
<!-- This file defines the gradient used on the background of the main activity. -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:type="linear"
                android:startColor="@color/app_color_light_background"
                android:endColor="@color/app_color_disabled"
                android:angle="90" />

            <!-- Round the top corners. -->
            <corners
                android:topLeftRadius="@dimen/radius_small"
                android:topRightRadius="@dimen/radius_small" />
        </shape>
    </item>
</selector>
edwoollard
  • 12,245
  • 6
  • 43
  • 74
Phil Ringsmuth
  • 2,037
  • 4
  • 20
  • 29
0

In Layout Make your ImageView like:

<com.example..CircularImageView
    android:id="@+id/profile_image_round_corner"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:scaleType="fitCenter"
    android:padding="2dp"
    android:background="@null"
    android:adjustViewBounds="true"
    android:layout_centerInParent="true"
    android:src="@drawable/dummy"
    />

And Create a Class:

package com.example;

import java.util.Formatter.BigDecimalLayoutForm;

import android.content.Context;
import android.graphics.Bitmap;
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 CircularImageView extends ImageView {

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

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

    public CircularImageView(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(), h = getHeight();

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

    }

    public static Bitmap getRoundBitmap(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, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xffa19774;
        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("#BAB399"));
        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;
    }

}
Max Base
  • 639
  • 1
  • 7
  • 15
Droid_Mechanic
  • 1,474
  • 14
  • 13
0

If any of you are facing this problem

enter image description here

Most probably , you are using Android Studio. Due to image re-size and all in Android Studio ,you may encounter this problem. An easy fix to this problem is to decrease the radius of circle in drawCircle(). In my case i use this fix

Using canvas.drawCircle(100, 100, 90, paint); instead of canvas.drawCircle(100, 100, 100, paint); this will definitely solve your problem.

Here is finally edited code:-

  public class Profile extends ActionBarActivity {


    TextView username;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);


        username= (TextView) findViewById(R.id.txt);

        String recievedusername=getIntent().getExtras().getString("toname");
        username.setText(recievedusername);


        Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.mipmap.gomez);

        Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, 200,200, false);
        Bitmap conv_bm=getCircleBitmap(resizedBitmap,100);
        // set circle bitmap
        ImageView mImage = (ImageView) findViewById(R.id.profile_image);
        mImage.setImageBitmap(conv_bm);
        // TODO Auto-generated method stub
    }
    private Bitmap getCircleBitmap(Bitmap bitmap , int pixels) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final 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());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(100,100, 90, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        bitmap.recycle();
        return output;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_apploud, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_addnew) {
            Intent i;
            i=new Intent(Profile.this,ApplaudSomeone.class);
            startActivity(i);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
kumar kundan
  • 2,027
  • 1
  • 27
  • 41
0

Try this

Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                finalBitmap.getHeight() / 2 + 0.7f,
                finalBitmap.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(
                android.graphics.PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
Bhavinkumar Patel
  • 515
  • 1
  • 12
  • 28
0
    /**
 * Background Async task to load user profile picture from url
 */
private class LoadProfileImage extends AsyncTask<String, Void, RoundedBitmapDrawable> {
    ImageView profileImageView;

    public LoadProfileImage(ImageView profileImageView) {
        this.profileImageView = profileImageView;
    }

    protected RoundedBitmapDrawable doInBackground(String... urls) {
        String photoUrl = urls[0];
        RoundedBitmapDrawable profileRoundedDrawable = null;
        try {
            InputStream inputStream = new java.net.URL(photoUrl).openStream();
            Resources res = getResources();

            profileRoundedDrawable = RoundedBitmapDrawableFactory.create(res, inputStream);
            profileRoundedDrawable.setCircular(true);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return profileRoundedDrawable;
    }

    protected void onPostExecute(RoundedBitmapDrawable result) {
        profileImageView.setImageDrawable(result);
    }
}
0

While the first two answers work, I wish to describe a bit more. Say, you have an activity or a fragment where your ImageView lies. You wish to draw an image and scale it proportionally. Then you should write in onCreate or onCreateView the following:

LinearLayout rootLayout = (LinearLayout) findViewById(R.id.rootLayout);
ImageView image = (ImageView) findViewById(R.id.image);
// Wait till an activity is visible and image can be measured.
rootLayout.post(new Runnable() {
    @Override
    public void run() {
        // Setting ImageView height with aspect ratio.
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.your_image);
        int height = getImageViewHeight(drawable, image);

        // Rounding image corners.
        float radius = getResources().getDimension(R.dimen.your_radius_in_dp);
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        Bitmap result = getRoundedBitmap(bitmap, image.getWidth(), height, radius);
        image.setImageBitmap(result);
    }
});

Where setting a new image height is:

public static int getImageViewHeight(Drawable drawable, ImageView imageView) {
    imageView.setImageDrawable(drawable);
    int width = drawable.getIntrinsicWidth();
    int height = 0;
    if (width > 0) {
        height = (drawable.getIntrinsicHeight() * imageView.getWidth()) / width;
        imageView.getLayoutParams().height = height;
        imageView.requestLayout();
    }
    return height;
}

Then you should write a method to scale an image and round its corners. Here width and height are new dimensions of a bitmap (smaller or larger). In the following example I round only two top corners.

private Bitmap getRoundedBitmap(Bitmap bitmap, int width, int height, float radius) {
    // Create scaled bitmap.
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
    BitmapShader shader = new BitmapShader(scaledBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);

    Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(result);
    // First make all corners round.
    canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
    // Then draw bottom rectangle.
    canvas.drawRect(0, height - radius, radius, height, paint);
    canvas.drawRect(width - radius, height - radius, width, height, paint);
    return result;
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224
0

here my solution:

<com.myproject.ui.RadiusCornerImageView
        android:id="@+id/imageViewPhoto"
        android:layout_width="160dp"
        android:layout_height="160dp"
        app:corner_radius_dp="5"
        app:corner_radius_position="top"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

And in java code:

public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

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

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

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);

    } else {
        throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
    }
    clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
 }
}
Jamil Hasnine Tamim
  • 4,389
  • 27
  • 43
Alex
  • 633
  • 1
  • 7
  • 18
  • This work around worked for me but it created another issue, the images displayed were doubled. Means i can see main image in center but there will be one more image in background. – Akshay Dec 13 '17 at 17:54
0

I used a Path to draw only corners on the image Canvas. (I needed solution with no bitmap memory allocation)

@Override
protected void onDraw(final Canvas canvas) {
    super.onDraw(canvas);

    if (!hasRoundedCorners()) return;

    mPaint.setStyle(Paint.Style.FILL);
    mPaint.setStrokeWidth(0);

    Path path = new Path();
    path.setFillType(Path.FillType.INVERSE_WINDING);
    path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRadius, mRadius, Path.Direction.CCW);
    canvas.drawPath(path, mPaint);
}

Notice that you should not allocate any new object in onDraw method. This code is a proof of concept and should not be used like this in product code

See more: https://medium.com/@przemek.materna/rounded-image-view-no-bitmap-reallocation-11a8b163484d

Max Base
  • 639
  • 1
  • 7
  • 15
Cililing
  • 4,303
  • 1
  • 17
  • 35
0

For me the following solution seems to be the most elegant:

ImageView roundedImageView = new ImageView (getContext());
roundedImageView.setClipToOutline(true);
Bitmap bitmap = AppUtil.decodeSampledBitmapFromResource(new File(valueListItemsView.getImagePath()), width, height);
roundedImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
roundedImageView.setImageBitmap(bitmap);
roundedImageView.setBackgroundResource(R.drawable.rounded_corner);

and the code for the rounded_corner.xml drawable is :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorAccent" />
    <corners android:radius="24dp" />
</shape>
Max Base
  • 639
  • 1
  • 7
  • 15
aurelianr
  • 538
  • 2
  • 12
  • 35
0

Kotlin Version:

@GlideExtension
object GamersGeekGlideExtension {

    @NonNull
    @JvmStatic
    @GlideOption
    fun roundedCorners(options: BaseRequestOptions<*>, context: Context, cornerRadius: Int): BaseRequestOptions<*> {
        val px =
            (cornerRadius * (context.resources.displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)).roundToInt()
        return options.transforms(RoundedCorners(px))
    }
}

Note: Glide Extensions now requires BaseRequestOptions instead of RequestOptions. Also, its the same function as @Sir Codesalot answer just converted in kotlin.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Junia Montana
  • 443
  • 7
  • 11
0

It can be easily done with the following shape. Add it as a src to your image. If you want to remove the border simply add your background color to the border ;-)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/img_area_one"
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <item>
        <shape
            android:padding="10dp"
            android:shape="rectangle">
            <corners
                android:topLeftRadius="8dp"
                android:topRightRadius="8dp"
                />
            <stroke
                android:width="5dp"
                android:color="@color/white" />
        </shape>
    </item>
</layer-list> 
Kasun Thilina
  • 1,523
  • 2
  • 14
  • 20
0

If you don't want to border affects the image, use this class. Unfortunately, I didn't find any approach to draw a transparent area on the canvas came to onDraw(). So, here is created a new bitmap and it's drawn on a real canvas.

The view is useful if you want to make a disappearing border. If you set borderWidth to 0, the border will disappear and the image remains with rounder corners exactly like the border was. I.e. it looks like the border is drawn exactly by the image edges.

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView


class RoundedImageViewWithBorder @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {

    var borderColor: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var borderWidth: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var cornerRadius: Float = 0f
        set(value) {
            invalidate()
            field = value
        }

    private var bitmapForDraw: Bitmap? = null
    private var canvasForDraw: Canvas? = null
    private val transparentPaint = Paint().apply {
        isAntiAlias = true
        color = Color.TRANSPARENT
        style = Paint.Style.STROKE
        xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
    }

    private val borderPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
    }

    private val transparentAreaRect = RectF()
    private val borderRect = RectF()

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageViewWithBorder)

        try {
            borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_border_width, 0)
            borderColor = typedArray.getColor(R.styleable.RoundedImageViewWithBorder_border_color, 0)
            cornerRadius = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_corner_radius, 0).toFloat()

        } finally {
            typedArray.recycle()
        }
    }

    @SuppressLint("CanvasSize", "DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        if (canvas.height <=0 || canvas.width <=0) {
            return
        }

        if (canvasForDraw?.height != canvas.height || canvasForDraw?.width != canvas.width) {
            val newBitmap = Bitmap.createBitmap(canvas.width, canvas.height, Bitmap.Config.ARGB_8888)
            bitmapForDraw = newBitmap
            canvasForDraw = Canvas(newBitmap)
        }
        
        bitmapForDraw?.eraseColor(Color.TRANSPARENT)

        // Draw existing content
        super.onDraw(canvasForDraw)

        if (borderWidth > 0) {
            canvasForDraw?.let { drawWithBorder(it) }
        } else {
            canvasForDraw?.let { drawWithoutBorder(it) }
        }

        // Draw everything on real canvas
        bitmapForDraw?.let { canvas.drawBitmap(it, 0f, 0f, null) }
    }

    private fun drawWithBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = borderWidth.toFloat() * 4
        transparentAreaRect.apply {
            left = -borderWidth.toFloat() * 1.5f
            top = -borderWidth.toFloat() * 1.5f
            right = canvas.width.toFloat() + borderWidth.toFloat() * 1.5f
            bottom = canvas.height.toFloat() + borderWidth.toFloat() * 1.5f
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, borderWidth.toFloat() * 2 + cornerRadius, borderWidth.toFloat() * 2 + cornerRadius, transparentPaint)

        // Draw border
        borderPaint.color = borderColor
        borderPaint.strokeWidth = borderWidth.toFloat()
        borderRect.apply {
            left = borderWidth.toFloat() / 2
            top = borderWidth.toFloat() / 2
            right = canvas.width.toFloat() - borderWidth.toFloat() / 2
            bottom = canvas.height.toFloat() - borderWidth.toFloat() / 2
        }
        canvas.drawRoundRect(borderRect, cornerRadius - borderWidth.toFloat() / 2, cornerRadius - borderWidth.toFloat() / 2, borderPaint)
    }

    private fun drawWithoutBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = cornerRadius * 4
        transparentAreaRect.apply {
            left = -cornerRadius * 2
            top = -cornerRadius * 2
            right = canvas.width.toFloat() + cornerRadius * 2
            bottom = canvas.height.toFloat() + cornerRadius * 2
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, cornerRadius * 3, cornerRadius * 3, transparentPaint)
    }

}

In values:

<declare-styleable name="RoundedImageViewWithBorder">
    <attr name="corner_radius" format="dimension|string" />
    <attr name="border_width" format="dimension|reference" />
    <attr name="border_color" format="color|reference" />
</declare-styleable>
Fox
  • 417
  • 4
  • 13
0

You can use the new ShapableImageView provided in newer versions of Android Material library.

For this, you first need to add the below dependency in your app level build.gradle file

implementation 'com.google.android.material:material:<version>'

Also, make sure that this app level build.gradle file is having Google's Maven Repository google() as below

allprojects {
repositories {
  google()
  jcenter()
}

}

Now after this, you can refer this resource to implement the imageview of your desired type or shape.

Prateek Sharma
  • 312
  • 3
  • 5