-7

Currently there are so many ways to create a Circle Bitmap in Android. But none of them are working for rectangle bitmap image. Even the Android API RoundedBitmapDrawable doesn't help much.

Basically this kotlin extension function will solve the issue.

albeee
  • 1,452
  • 1
  • 12
  • 20

1 Answers1

-1
fun Bitmap.cropToCircle(): Bitmap {
    val circleBitmap = if (this.width > this.height) {
        Bitmap.createBitmap(this.height, this.height, Bitmap.Config.ARGB_8888)
    } else {
        Bitmap.createBitmap(this.width, this.width, Bitmap.Config.ARGB_8888)
    }
    val bitmapShader = BitmapShader(this, TileMode.CLAMP, TileMode.CLAMP)
    val paint = Paint().apply {
        isAntiAlias = true
        shader = bitmapShader
    }
    val radius = if (this.width > this.height) {
        this.height / 2f
    } else {
        this.width / 2f
    }
    Canvas(circleBitmap).apply {
        drawCircle(radius, radius, radius, paint)
    }
    this.recycle()
    return circleBitmap
}   

Hope this helps someone!
albeee
  • 1,452
  • 1
  • 12
  • 20