Android基于Path的addRoundRect,Canvas剪切clipPath简洁的圆形图实现,Kotlin(2)
Kotlin
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Path
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
class MyView : AppCompatImageView {
private var mRadius = 0f //半径
private val mPath = Path()
constructor(ctx: Context, attributeSet: AttributeSet) : super(ctx, attributeSet) {
val mBmpSrc = BitmapFactory.decodeResource(resources, R.mipmap.pic, null)
setImageBitmap(mBmpSrc)
}
override fun onDraw(canvas: Canvas) {
canvas.save()
val w = measuredWidth.toFloat()
val h = measuredHeight.toFloat()
val mini = Math.min(w, h)
mRadius = mini / 2f
val left = (w - mini) / 2f
val top = (h - mini) / 2f
val right = (w + mini) / 2f
val bottom = (h + mini) / 2f
mPath.addRoundRect(left, top, right, bottom, mRadius, mRadius, Path.Direction.CW)
canvas.clipPath(mPath)
super.onDraw(canvas)
canvas.restore()
}
}