Search code examples
androidimageviewandroid-imageviewcroprounded-corners

ImageView with rounded corners after scaling with ScaleType.CenterCrop


I am trying to crop an image and then round the corners so that it appears more nicely on the screen.

What I've been able to do is round the corners of the image, but the cropping will sometimes cut off the sides of the image (depending on the size/aspect ratio of the image).

So what I would like to do is perform the crop, THEN apply the rounded corners. How can I do this?

Rounding the corners of the image:

private Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff000000;
    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 = 20;

    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;
}

And then I set the imageview's scaletype like so: imageView.setScaleType(ScaleType.CENTER_CROP)


Solution

  • if you wrap your imageview with cardview, you achieve.

    <android.support.v7.widget.CardView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="4dp"
        card_view:cardUseCompatPadding="true">
            <ImageView
                android:id="@+id/ivImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/your_image" />
    </android.support.v7.widget.CardView>