XML
文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<com.yang.app.MyView
android:id="@+id/iv"
android:layout_width="300dp"
android:layout_height="300dp"/>
</LinearLayout>
自定义View
代码
class MyView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val spanValue = 200f
private val mNewPaint = Paint().apply {
isAntiAlias = true
isFilterBitmap = true
style = Paint.Style.STROKE
strokeWidth = 10f
color = Color.RED
}
private val mOldPaint = Paint().apply {
isAntiAlias = true
isFilterBitmap = true
style = Paint.Style.STROKE
strokeWidth = 10f
color = Color.BLUE
}
private val mFinalPaint = Paint().apply {
isAntiAlias = true
isFilterBitmap = true
style = Paint.Style.STROKE
strokeWidth = 10f
color = Color.GREEN
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawRect(0f, 0f, width.toFloat(), height.toFloat(), mNewPaint)
canvas?.drawRect(0f, 0f, spanValue, spanValue, mOldPaint)
val matrix = Matrix()
matrix.setTranslate((width / 2).toFloat(), (height / 2).toFloat())
canvas?.concat(matrix)
canvas?.drawCircle(0f, 0f, 20f, Paint().apply {
color = Color.BLACK
})
canvas?.drawRect(-spanValue/2, -spanValue/2, spanValue/2, spanValue/2, mNewPaint)
matrix?.invert(matrix)
canvas?.concat(matrix)
canvas?.drawRect(0f, 0f, spanValue * 2, spanValue * 2, mFinalPaint)
}
}
效果图
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/e30c2e9af8364cf798a17d24db2f6351.png)