android实现不规则区域点击

定义好一个圆形的path

mPath = Path()
mPath.addCircle(0f, 0f, 200f, Path.Direction.CW)

获取path的边界

 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)

画path

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.translate(mWidth / 2f, mHeight / 2f)
    //这里也需要平移,否则点击区域会出错
    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, "圆形区域点击", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "圆形外部区域点击", 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)
        //这里也需要平移,否则点击区域会出错
        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, "圆形区域点击", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "圆形外部区域点击", 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()
    }
}

你可能感兴趣的:(android实现不规则区域点击)