bitmap circular crop in android

12,127

Solution 1

have a look at RoundedBitmapDrawable in the support library

all you have to do is give it the bitmap and the corner radius

RoundedBitmapDrawable img = RoundedBitmapDrawableFactory.create(getResources(),bitmap);
img.setCornerRadius(radius);

imageView.setImageDrawable(img);

Solution 2

You Can make your imageview circular using RoundedBitmapDrawable

here is the code for achieving roundedImageview:

ImageView profilePic=(ImageView)findViewById(R.id.user_image);
//get bitmap of the image
Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),  R.drawable.large_icon);
RoundedBitmapDrawable roundedBitmapDrawable=
  RoundedBitmapDrawableFactory.create(getResources(), imageBitmap);
roundedBitmapDrawable.setCornerRadius(50.0f);
roundedBitmapDrawable.setAntiAlias(true);
profilePic.setImageDrawable(roundedBitmapDrawable);

Solution 3

You can use the power of PorterDuff to get your bitmap in any shape or path...

Here is an example:

public static Bitmap getCircular(Bitmap bm, int cornerRadiusPx) {
    int w = bm.getWidth();
    int h = bm.getHeight();

    int radius = (w < h) ? w : h;
    w = radius;
    h = radius;

    Bitmap bmOut = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmOut);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(0xff424242);

    Rect rect = new Rect(0, 0, w, h);
    RectF rectF = new RectF(rect);

    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(rectF.left + (rectF.width()/2), rectF.top + (rectF.height()/2), radius / 2, paint);

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

    return bmOut;
}
Share:
12,127
sara roberts
Author by

sara roberts

Updated on June 28, 2022

Comments

  • sara roberts
    sara roberts almost 2 years

    I have a square bitmap being displayed underneath a semi-transparent circle. The user can touch and drag the bitmap to position it. I want to be able to crop what ever part of the bitmap is under the circle. How can I do this?

  • tyczj
    tyczj over 9 years
    its probably better to use RoundedBitmapDrawable now instead of doing it manually
  • sara roberts
    sara roberts over 9 years
    @Nitesh- how can i change it to a circle?
  • crubio
    crubio over 8 years
    Instead of using a constant corner radius you should use: roundedBitmapDrawable.setCornerRadius(Math.min(roundedBitmap‌​Drawable.getMinimumW‌​idth(), roundedBitmapDrawable.getMinimumHeight())/2.0f);
  • Roel
    Roel over 8 years
    You can use setCircular(true) if you want it to be circular.
  • Roel
    Roel over 8 years
    You can img.setCircular(true) instead of img.setCornerRadius(radius) if you want it to be perfect circular.
  • Themos
    Themos about 4 years
    Best answer out there for pure code solution, no XML modification or custom shapes necessary