Compaq LE2202x
Compaq LE2202x

Reputation: 2376

How to make the corner of an image inside ImageView round?

I am having this problem and I know it's common, the problem is that I have already applied the code to draw, here. Now, since my ImageView has set width and height which is 50dp, the rounded corner is not achieved.

So I used the xml alternative, here it is:

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

I made this as background of the ImageView, the problem now is that the only affected of the round corner is the ImageView itself and not its content image. The image's normal (rectangle or sharp) edge still overlapped its container which is the ImageView. I also set this android:scaleType="centerCrop" in my ImageView.

I am now confused, so setting the ImageView's width and height forfeits the effect of the rounded corner? What should I do?

Upvotes: 0

Views: 1716

Answers (2)

Gopal Gopi
Gopal Gopi

Reputation: 11131

try this...

public static Bitmap getRoundCorneredBitmapFrom(Bitmap bitmap,int cornerRadius)  {
        if (bitmap == null) {
            return null;
        }
        if (cornerRadius < 0) {
            cornerRadius = 0;
        }
        // Create plain bitmap
        Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = getCanvas(canvasBitmap);

        Paint paint = getPaint();

        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(rect);

        canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);

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

        return canvasBitmap;
    }
  private static Canvas getCanvas(Bitmap bitmap) {
     Canvas canvas = new Canvas(bitmap);
     canvas.drawARGB(0, 0, 0, 0);
     return canvas;
  }
  private static Paint getPaint() {
     Paint paint = new Paint();
     paint.setAntiAlias(true);
     paint.setColor(Color.WHITE);
     return paint;
 }

Upvotes: 1

Alhaytham Alfeel
Alhaytham Alfeel

Reputation: 111

Here's a complete example: https://github.com/vinc3m1/RoundedImageView

Check it out.

Upvotes: 2

Related Questions