如何在Android中从源位图裁剪圆位图?

问题描述 投票:0回答:1

经过大量的挖掘,发现以及反复试验的测试,我终于得出了这一kotlin扩展的结论。

android bitmap crop android-bitmap kotlin-android-extensions
1个回答
0
投票
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!
Try it out and let me know if you face any issues. 
Happy Coding :-)
© www.soinside.com 2019 - 2024. All rights reserved.