Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop Image as circle in Android

Does anyone know how to crop an image\bitmap to a circle? I can not find any solution, sorry ..

like image 247
AlexMrKlim Avatar asked Oct 17 '12 22:10

AlexMrKlim


3 Answers

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;
}
like image 132
Aj 27 Avatar answered Oct 18 '22 17:10

Aj 27


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 using Canvas.drawRoundRect(). The trick is to use a Paint with a BitmapShader 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);
like image 35
Scott W Avatar answered Oct 18 '22 17:10

Scott W


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

like image 35
Graham Smith Avatar answered Oct 18 '22 18:10

Graham Smith