Search code examples
androidcanvasxamarinregion

Do not understand Region class very well


I using xamarin to develop a android app. When I try to use Region class I got a problem, below code can work well and show a expected blue area.

Rect rect1 = new Rect(0, 0, 10,10);
canvas.ClipRect(rect1);
Rect rect2 = new Rect(20, 20, 30,30);
canvas.ClipRect(rect2, Region.Op.Union);
canvas.DrawRect(0, 0, 40, 40, paint);

But below code does not work, just show nothing, a blank background

Region region = new Region();
Rect rect1 = new Rect(0, 0, 10,10);
region.Union(rect1);
Rect rect2 = new Rect(20, 20, 30,30);
region.Union(rect2);

canvas.ClipRegion(region);
canvas.DrawRect(0, 0, 40, 40, paint);

I do not know why.


Solution

  • In fact it works, but it may be blocked by your ActionBar or something others, so you cant see it and you think it does not work, like this. But if you modify the coordinates you can see the rectangle which you draw. Here is my code and result:

    Region region = new Region();
    Rect rect1 = new Rect(200, 200, 300, 300);
    region.Union(rect1);
    Rect rect2 = new Rect(400, 400, 500, 500);
    region.Union(rect2);
    

    Here is the document to explain the canvas.ClipRegion(region) method:

    Intersect the current clip with the specified region. Note that unlike clipRect() and clipPath() which transform their arguments by the current matrix, clipRegion() assumes its argument is already in the coordinate system of the current layer's bitmap, and so not transformation is performed.

    EDIT :

    Coordinate for clipRect(), coornadite for clipRegion().