Monday, August 16, 2010

Rounding picture

Suppose we have an image and we would like to make it's corners rounded.
 The main idea is to combine the original image and already prepared rounded image with the same height and width, and use only those pixels from original image that are present at the rounded one:


Next code does that by using PorterDuffXfermode Xfermode:

/**
 * Creates rounded bitmap
 * @param bitmap the source bitmap
 * @return the rounded bitmap
 */
public static Bitmap createRoundedBitmap(Bitmap bitmap, int round) {
    if (bitmap == null) {
        return null;
    }
        
    Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    // create output bitmap
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);

    // assign canvas with output bitmap
    Canvas canvas = new Canvas(output);
    canvas.drawARGB(0, 0, 0, 0);
        
    // initialize paint
    Paint paint = new Paint();
    paint.setAntiAlias(true);

    // draw rounded rect to bitmap
    paint.setColor(0xFFFFFFFF);
    canvas.drawRoundRect(new RectF(rect), round, round, paint);

    // copy original bitmap to rounded area
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
        
    return output;
}


Notes
There was used an icon from Google weather API.
There are different modes for the Porter-Duff composing, and next picture from w3.org shows some of them:

1 comment:

  1. code is work fine. but all image are not same. so how can i set fix size image.

    ReplyDelete