Guide
Computing a Bounding Box with Android Rect.union
Learn how to combine two Android Rect objects into a bounding box using Rect.union, with steps for null safety, normalization, and verification. Note that union mutates the receiver.
Published by Tasadduq Burney
25 Jul 2026, 18:58 UTC
2 min44.6K views0

Desired Outcome
Obtain a single Rect that encloses two given rectangles, useful for bounding‑box calculations in UI layout or collision detection.
Prerequisites
- Android Studio or any JVM/Android build environment.
- Project targeting API level 1 or higher (the
Rect.unionmethod exists since API 1). - Two
android.graphics.Rectinstances (or the ability to create them).
Procedure
- Create or obtain the rectangles. Ensure they are not
null. If they come from UI components, callgetGlobalVisibleRector similar. - Normalize each rectangle (optional but recommended). If you suspect
left > rightortop > bottom, callrect.sort()to swap the coordinates so thatleft ≤ rightandtop ≤ bottom. - Decide whether to preserve the original rectangles.
- If you can mutate one of the inputs, call
rectA.union(rectB);directly. After the call,rectAholds the union. - If you need both originals unchanged, create a copy first:
This allocates a newRect unionRect = new Rect(rectA); unionRect.union(rectB);Rectand mutates the copy.
- If you can mutate one of the inputs, call
- Use the result. Pass the mutated rectangle (either
rectAorunionRect) to drawing APIs, layout calculations, or store it for later use.
Expected Checks
- Verify that the resulting rectangle's
leftequalsMath.min(rectA.left, rectB.left)and similarly fortop. - Verify that
rightequalsMath.max(rectA.right, rectB.right)andbottomequalsMath.max(rectA.bottom, rectB.bottom). - If either input rectangle is empty (
isEmpty()returns true), the union should be identical to the non‑empty rectangle (or empty if both are empty). - Log or assert these values in a unit test or debug output to confirm correctness.
Recovery Options
- Null argument. Guard the call:
if (rectA == null || rectB == null) { /* handle error */ } else { /* union */ }to avoidNullPointerException. - Non‑normalized rectangles. After union, inspect
width()andheight(). If either is negative, re‑normalize the inputs withsort()and repeat the union. - Unexpected empty result. Confirm that at least one rectangle had area; if both are empty, the union will be empty, which may be the intended outcome.
Limitations
- The instance method
union(Rect)mutates the receiver; it does not return a newRect. You must assign the return value of a copy constructor if you need the merged bounds without altering the original. - Union works only with axis‑aligned rectangles; it cannot represent rotated bounds.
- Because a new
Rectis allocated only when you explicitly copy, frequent use in tight loops can be made allocation‑free by reusing a mutableRectinstance.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.