Does anyone know how to crop an image\bitmap to a circle? I can not find any solution, sorry ..
For having rounded corners for ImageView, convert your image into bitmap and then try following code :
private Bitmap getRoundedCroppedBitmap(Bitmap bitmap) {
int widthLight = bitmap.getWidth();
int heightLight = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paintColor = new Paint();
paintColor.setFlags(Paint.ANTI_ALIAS_FLAG);
RectF rectF = new RectF(new Rect(0, 0, widthLight, heightLight));
canvas.drawRoundRect(rectF, widthLight / 2, heightLight / 2, paintColor);
Paint paintImage = new Paint();
paintImage.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
canvas.drawBitmap(bitmap, 0, 0, paintImage);
return output;
}
Romain Guy, formerly an engineer on the Android team at Google, posted an excellent article on drawing images with rounded corners. This idea could be easily extended to a circle, for example, by changing the rounded rectangle radius so that it creates a complete circle.
From the article:
To generate the rounded images I simply wrote a custom
Drawable
that draws a rounded rectangle usingCanvas.drawRoundRect()
. The trick is to use aPaint
with aBitmapShader
to fill the rounded rectangle with a texture instead of a simple color. Here is what the code looks like:BitmapShader shader; shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(shader); RectF rect = new RectF(0.0f, 0.0f, width, height); // rect contains the bounds of the shape // radius is the radius in pixels of the rounded corners // paint contains the shader that will texture the shape canvas.drawRoundRect(rect, radius, radius, paint);
Wiseman Designs, have an open source Circular ImageView ready for use
https://github.com/wisemandesigns/CircularImageView
This uses XML in your layouts, which makes life easier. You can set the source in XML or with some minor modification could easily use a Bitmap.
Disclaimer: I work for Wiseman Designs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With