androidandroid-viewandroid-canvasandroid-paintandroid-rect

Android. How to paint all area around of rectangle?


I have custom view and inside onDraw I need to draw in canvas rectangle. I have RectF with all coordinates. And now I need to paint the entire area around the rectangle in a different color. Is it possible to do this using RectF ?

Please help me.


Solution

  • To color red the outside of a 400 pixel by 400 pixel rectangle in the center of a view you can do the following in onDraw():

    val canvasCenter = Point(canvas.width / 2, canvas.height / 2)
    val r = Rect(
        canvasCenter.x - 200,
        canvasCenter.y - 200,
        canvasCenter.x + 200,
        canvasCenter.y + 200,
    )
    canvas.clipOutRect(r)
    canvas.drawColor(Color.RED)
    

    This code assumes that the view is at least 400px by 400px.

    See clipRect.