这是azizbekian答案的Kotlin版本:
class RoundedRelativeLayout(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
private lateinit var rectF: RectF
private val path = Path()
private var cornerRadius = 15f
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
rectF = RectF(0f, 0f, w.toFloat(), h.toFloat())
resetPath()
}
override fun draw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.draw(canvas)
canvas.restoreToCount(save)
}
override fun dispatchDraw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.dispatchDraw(canvas)
canvas.restoreToCount(save)
}
private fun resetPath() {
path.reset()
path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW)
path.close()
}
}
编辑
作为一个额外的xml属性,您可以添加cornerRadius,并将其设置为以下内容,只需将其添加到res/values/styleable.xml
中即可:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundedRelativeLayout">
<attr name="cornerRadius" format="float"/>
</declare-styleable>
</resources>
然后将此初始化方法添加到RoundedRelativeLayout
类中:
init {
val ta = getContext().obtainStyledAttributes(attrs, R.styleable.RoundedRelativeLayout)
cornerRadius = ta.getFloat(R.styleable.RoundedRelativeLayout_cornerRadius, 15f)
ta.recycle()
}
现在当您使用布局时,您可以在XML中像这样设置cornerRadius:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" <-- Make sure you include this line
android:layout_width="80dp"
android:layout_height="80dp">
.
.
.
<your.package.name.RoundedRelativeLayout
android:id="@+id/roundedRect"
app:cornerRadius="24"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
.
.
.