【问题标题】:How to crop circle bitmap from source bitmap in Android?如何从Android中的源位图裁剪圆形位图?
【发布时间】:2020-01-31 11:07:33
【问题描述】:
目前在 Android 中有很多方法可以创建圆形位图。但它们都不适用于矩形位图图像。甚至 Android API RoundedBitmapDrawable 也无济于事。
这个kotlin扩展功能基本上可以解决问题。
【问题讨论】:
标签:
android
bitmap
crop
android-bitmap
kotlin-android-extensions
【解决方案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!