I think it will work fine when the input bitmap to be a perfect square (same height and width) which give perfect circle but if your bitmap is in rectangle-shaped or width is more then height than it creates a problem. I have modified the code to into kotlin also added a border to it only you need to give input as bitmap
private fun getCircleBitmap(bitmap: Bitmap): Bitmap
{
var srcRect: Rect
var dstRect: Rect
var r: Float
var paint = Paint();
var width: Int = bitmap.getWidth()
var height: Int = bitmap.getHeight()
var widthToGenerate = 100F
var heightToGenerate = 100F
var borderWidth: Float = 1.toFloat()
var output: Bitmap
var canvas: Canvas
if (width > height) {
output = Bitmap.createBitmap(widthToGenerate.toInt(), heightToGenerate.toInt(), Bitmap.Config.ARGB_8888);
canvas = Canvas(output);
val scale: Float = (widthToGenerate / width)
var xTranslation = 0.0f
var yTranslation: Float = (heightToGenerate - height * scale) / 2.0f;
var transformation = Matrix();
transformation.postTranslate(xTranslation, yTranslation)
transformation.preScale(scale, scale)
var color: Int = Color.WHITE
paint.setAntiAlias(true)
paint.setColor(color)
canvas.drawBitmap(bitmap, transformation, paint)
} else {
output = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888)
canvas = Canvas(output);
var top: Int = (height - width) / 2
var bottom: Int = top + width
srcRect = Rect(0, top, width, bottom)
dstRect = Rect(0, 0, width, width);
r = (width / 2).toFloat()
var color: Int = Color.GRAY
paint.setAntiAlias(true)
canvas.drawARGB(0, 0, 0, 0)
paint.setColor(color)
canvas.drawCircle(r + borderWidth, r + borderWidth, r + borderWidth, paint)
canvas.drawCircle(r, r, r, paint)
paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC_IN))
canvas.drawBitmap(bitmap, srcRect, dstRect, paint)
bitmap.recycle()
}
return output
}
notifiation_drawable.xml file for border
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="2.0"
android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke
android:width="2dp"
android:color="@android:color/darker_gray" />
</shape>