Last active
August 29, 2015 14:16
-
-
Save omatt/f3c8dba475f32cf9280a to your computer and use it in GitHub Desktop.
Circle Crop Effect on Bitmap. Designed specifically for Android ImageViews.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a Bitmap object with a circle crop effect. | |
* This can be used in an ImageView and it must use | |
* "centerCrop" on its scaleType to achieve desired output. | |
* <p> | |
* Reference: {@link} http://stackoverflow.com/a/14051472/2497859 | |
* | |
* @param bitmap The bitmap that we're going to "circle crop" | |
* @return Bitmap with a circle crop overlay | |
* @see android.graphics.Bitmap | |
*/ | |
private static Bitmap getCircleCroppedBitmap(Bitmap bitmap) { | |
// use scaleType="centerCrop" on the ImageView to generate desire output | |
Bitmap output = null; | |
try { | |
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.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()); | |
paint.setAntiAlias(true); | |
canvas.drawARGB(0, 0, 0, 0); | |
paint.setColor(color); | |
if(bitmap.getWidth() < bitmap.getHeight() ) { | |
// Bitmap is in portrait | |
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, | |
bitmap.getWidth() / 2, paint); | |
} else{ | |
// Bitmap is in landscape or has a 1:1 aspect ratio | |
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, | |
bitmap.getHeight() / 2, paint); | |
} | |
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); | |
canvas.drawBitmap(bitmap, rect, rect, paint); | |
} catch (Exception e){ | |
Log.e(TAG, "getCircleCroppedBitmap " + e); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment