Skip to content

Instantly share code, notes, and snippets.

@jewelzqiu
Last active December 13, 2023 01:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jewelzqiu/c0633c9f3089677ecf85 to your computer and use it in GitHub Desktop.
Save jewelzqiu/c0633c9f3089677ecf85 to your computer and use it in GitHub Desktop.
Crop a bitmap to circle in Android
public static Bitmap getCircledBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
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);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
@typebrook
Copy link

Works out of the box, thanks man!

@Ahror
Copy link

Ahror commented Aug 26, 2020

Thanks man)) Works great!

@kirmartuk
Copy link

kirmartuk commented Jan 9, 2021

Kotlin

    /**
     * Convert square bitmap to circle
     * @param Bitmap - square bitmap
     * @return circle bitmap
     */
    fun Bitmap.getCircledBitmap(): Bitmap {
        val output = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        val paint = Paint()
        val rect = Rect(0, 0, this.width, this.height)
        paint.isAntiAlias = true
        canvas.drawARGB(0, 0, 0, 0)
        canvas.drawCircle(this.width / 2f, this.height / 2f, this.width / 2f, paint)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(this, rect, rect, paint)
        return output
    }

@AlekSt7
Copy link

AlekSt7 commented Oct 28, 2021

It works fine, you saved my project, thank you!

@kabirnayeem99
Copy link

Thanks man, it works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment