定義好一個(gè)圓形的path
mPath = Path()
mPath.addCircle(0f, 0f, 200f, Path.Direction.CW)
獲取path的邊界
val bounds = RectF()
mPath.computeBounds(bounds, true)
生成可點(diǎn)擊區(qū)域的范圍
val region = Region(
bounds.left.toInt(),
bounds.top.toInt(),
bounds.right.toInt(),
bounds.bottom.toInt()
)
mCircleRegion = Region()
mCircleRegion.setPath(mPath, region)
畫(huà)path
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.translate(mWidth / 2f, mHeight / 2f)
//這里也需要平移,否則點(diǎn)擊區(qū)域會(huì)出錯(cuò)
mCircleRegion.translate(mWidth / 2, mHeight / 2)
canvas?.drawPath(mPath, mPaint)
}
點(diǎn)擊事件
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_UP -> {
if (mCircleRegion.contains(event.x.toInt(), event.y.toInt())) {
Toast.makeText(context, "圓形區(qū)域點(diǎn)擊", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "圓形外部區(qū)域點(diǎn)擊", Toast.LENGTH_SHORT).show()
}
}
}
return true
}
完整代碼
class CircleButton : View {
lateinit var mPaint: Paint
lateinit var mPath: Path
lateinit var mCircleRegion: Region
var mWidth = 0
var mHeight = 0
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
private fun init() {
mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
mPaint.color = Color.parseColor("#3700B3")
mPaint.style = Paint.Style.FILL
mPath = Path()
mPath.addCircle(0f, 0f, 200f, Path.Direction.CW)
val bounds = RectF()
mPath.computeBounds(bounds, true)
val region = Region(
bounds.left.toInt(),
bounds.top.toInt(),
bounds.right.toInt(),
bounds.bottom.toInt()
)
mCircleRegion = Region()
mCircleRegion.setPath(mPath, region)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.translate(mWidth / 2f, mHeight / 2f)
//這里也需要平移,否則點(diǎn)擊區(qū)域會(huì)出錯(cuò)
mCircleRegion.translate(mWidth / 2, mHeight / 2)
canvas?.drawPath(mPath, mPaint)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_UP -> {
if (mCircleRegion.contains(event.x.toInt(), event.y.toInt())) {
Toast.makeText(context, "圓形區(qū)域點(diǎn)擊", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "圓形外部區(qū)域點(diǎn)擊", Toast.LENGTH_SHORT).show()
}
}
}
return true
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
init()
}
}