raju
raju

Reputation: 1264

how to convert the square shape image into oval shape

In my application I am taking the image from the gallery and the shape of that image is in square I want to set that image to an imageView then it should be oval shape. I.e in my case I need to crop that image like human face. can anybody tell me how to do that thanks in advance.

Upvotes: 0

Views: 4643

Answers (2)

Hussain
Hussain

Reputation: 5562

Use the following class instead of image view.

 RoundedCornerImageView imageView1;
 imageView1.setRadius(10);

This will make the image radius by 10 px, you can give wat value you want and make it as the shape you want. Have a try.

All the best :)

public class RoundedCornerImageView extends ImageView {
    private int radius = 10;

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

    protected void onDraw(Canvas canvas) {
        Path clipPath = new Path();
        int w = this.getWidth();
        int h = this.getHeight();
        clipPath.addRoundRect(new RectF(0, 0, w, h), radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }

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

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

    public void setRadius(int radius){
        this.radius = radius;
        this.invalidate();
    }
}

Upvotes: 5

Abhinav Singh Maurya
Abhinav Singh Maurya

Reputation: 3313

You can use this

public  Drawable getRoundedCornerImage(Drawable bitmapDrawable) {
        Bitmap bitmap = ((BitmapDrawable)bitmapDrawable).getBitmap();
        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 = 100;

        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);
        Drawable image = new BitmapDrawable(output);
        return image;

    }

Hope this helps you

Upvotes: 4

Related Questions