1

I want to be able to center-crop a rectangle image into a circle. I have managed to do it but I'm sure there's more efficient way of doing it? Here's my code:

Center Crop:

    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger
    // of these two.

    int newWidth = 300;
    int newHeight  = 300;

    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
   Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

Once I have created this new center-cropped Bitmap, I now want to make it circular. I pass the bitmap from above into this method:

    public Bitmap getRoundedBitmap(Bitmap bitmap) {
    final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(output);

    final int color = Color.RED;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawOval(rectF, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    bitmap.recycle();
    return output;
    }

Is it possible to combine these methods together? I'm fairly new to Bitmap manipulation. Thanks!

Creating another bitmap then manipulating in the getRoundedBitmap() method seems to be unnecessary.

1 Answers1

0

This answer might help you (it shows the code of a RoundedImageView class): https://stackoverflow.com/a/16208548/1370336

Community
  • 1
  • 1
Remy Cilia
  • 2,573
  • 1
  • 20
  • 31