Search code examples
androidrect

Why does Rect.contains(right,bottom) returns false?


I am debugging a problem with my touchcode and I stumbled upon this weird behaviour of the Rect class.

Rect rect = new Rect(0,0,10,10);
rect.contains(0,0)   // true
rect.contains(10,10) // false
rect.contains(9,9)   // true

Why is this happening??!

Why are the right and bottom bounds exclusive and the left and top inclusive? I don't find it logical, and there is no documentation that notes this.


Solution

  • This is expected/documented. From the contains(int, int) reference:

    The left and top are considered to be inside, while the right and bottom are not. This means that for a x,y to be contained: left <= x < right and top <= y < bottom.

    Although I agree this seems a little illogical, it makes more sense when you consider an edge case:

    An empty rectangle never contains any point.

    This behavior also prevents a single x,y point from being contained within multiple, non-intersecting Rects.