android开发使用clipPath快速实现ImageView圆角

class RoundImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

private val mRadius = 10f
private val mRoundedRectPath = Path()
private var width = 0f
private var height = 0f
private var isClip = false

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
width = measuredWidth * 1.0f
height = measuredHeight * 1.0f
}

override fun onDraw(canvas: Canvas) {
if (!isClip) {
isClip = true
mRoundedRectPath.reset()
mRoundedRectPath.moveTo(mRadius, 0f)
mRoundedRectPath.lineTo(width - mRadius, 0f)
mRoundedRectPath.quadTo(width, 0f, width, mRadius)
mRoundedRectPath.lineTo(width, height)
mRoundedRectPath.lineTo(0f, height)
mRoundedRectPath.lineTo(0f, mRadius)
mRoundedRectPath.quadTo(0f, 0f, mRadius, 0f)
}
try {
canvas.clipPath(mRoundedRectPath)
super.onDraw(canvas)
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
 

 

原文地址:https://www.cnblogs.com/yongfengnice/p/13673423.html