Simple way to create a Rounded Corner Image in Android

By | July 22, 2018

RoundRectCornerImageView

Rounded Image - Android


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;

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

    private float radius = 14.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();
        rect = new RectF();
    }

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

Usage in XML

 <your_package.RoundRectCornerImageView 
      android:id="@+id/image" 
      android:layout_width="@dimen/thumbnail_dimension" 
      android:layout_height="@dimen/thumbnail_dimension" />

Done

One thought on “Simple way to create a Rounded Corner Image in Android

Leave a Reply

Your email address will not be published. Required fields are marked *