Skip to content

Instantly share code, notes, and snippets.

@ryanbateman
Created October 16, 2012 15:06
Show Gist options
  • Save ryanbateman/3899841 to your computer and use it in GitHub Desktop.
Save ryanbateman/3899841 to your computer and use it in GitHub Desktop.
Round and frame an image
public static Bitmap round(Context context, Bitmap source) {
// Use the height and width of our source image as a basis
int width = source.getWidth();
int height = source.getHeight();
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(WHITE);
// Create a circle mask canvas to trim the source image
Bitmap clipped = Bitmap.createBitmap(width, height, ARGB_8888);
Canvas canvas = new Canvas(clipped);
canvas.drawCircle(width/2, height/2, (width/2) - convertDPsToPixels(context, 5), paint);
// Change the PorterDuffmode to trim the correct part of the image
paint.setXfermode(new PorterDuffXfermode(DST_IN));
// Create a clipped bitmap
Bitmap rounded = Bitmap.createBitmap(width, height, ARGB_8888);
canvas = new Canvas(rounded);
canvas.drawBitmap(source, 0, 0, null);
canvas.drawBitmap(clipped, 0, 0, paint);
// Create a bitmap to hold the framed bitmap, allowing for 1dp of shadow
Bitmap framed = Bitmap.createBitmap(width, height, ARGB_8888);
canvas = new Canvas(framed);
paint.setXfermode(null);
canvas.drawCircle(width/2, height/2, (width/2) - convertDPsToPixels(context, 1), paint);
canvas.drawBitmap(rounded, 0, 0, null);
// Create the bitmap onto which to draw the shadow circle and the clipped image
Bitmap shadowed = Bitmap.createBitmap(width, height, ARGB_8888);
canvas = new Canvas(shadowed);
paint.setColor(Color.LTGRAY);
canvas.drawCircle(width/2, height/2, width/2, paint);
canvas.drawBitmap(framed, 0, 0, null);
// Recycle our previous bitmaps to free up memory
clipped.recycle();
rounded.recycle();
framed.recycle();
return shadowed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment