Search code examples
androidmobileviewandroid-viewandroid-viewgroup

Android - get percentage of viewable rect


I'm trying to indicate whether a certain view (say - view A) is 100% visible, meaning, if it's a 100x100 view, I want to make sure all 10000 pixels are shown.

Sample:

--------------
|            |
|   ___      |
|   |A|      |
|   ---      |
|            |
--------------

Should return 100% whereas:

--------------
|            |
|   _________|_________
|   |A       |         |
|   ---------|---------
|            |
--------------

Should return roughly 50%.

I've tried measuring globalVisibleRect, localVisibleRect, hitTest, drawableRect, focusableRect, and they are all the same, no matter if the view is totally visible or not.

Any ideas?


Solution

  • If you get the co-ordinates of the views, you can easily compute the area of the intersection:

    intersectionArea = max(0, max(AX2, BX2) - min(AX1, BX1)) * max(0, max(AY2, BY2) - min(AY1, BY1))
    

    From this, you can compute the area used by the union:

    unionArea = AreaA + AreaB - intersectionArea

    And you can then determine the ratio of this area

    intersectionArea / unionArea