XML
文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<com.yang.openglesproject.RoundedCornerView
android:layout_width="200dp"
android:layout_height="200dp"
app:viewCornerRadius="30dp" />
</LinearLayout>
Resources
配置文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundedCornerView">
<attr name="viewCornerRadius" format="dimension"/>
</declare-styleable>
</resources>
自定义View
代码
class RoundedCornerView @JvmOverloads constructor(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var mCornerRadius = 0f
private val mPath = Path()
init {
context.obtainStyledAttributes(attrs, R.styleable.RoundedCornerView, 0, 0).apply {
try {
mCornerRadius = getDimension(R.styleable.RoundedCornerView_viewCornerRadius, 60f)
} finally {
recycle()
}
}
}
override fun onDraw(canvas: Canvas) {
mPath.reset()
mPath.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()), mCornerRadius, mCornerRadius, Path.Direction.CW)
canvas.withSave {
canvas.clipPath(mPath)
canvas.drawColor(Color.parseColor("#ffffbb33"))
}
super.onDraw(canvas)
}
}