Using Android Rect for Hit‑Testing and Layout Calculations
Learn how to reuse android.graphics.Rect for efficient hit‑testing and layout work, with a code example and pitfalls to avoid.
12 Sept 2025, 04:08 UTC

Quick answer
Use android.graphics.Rect to store integer‑based bounds and reuse a single instance for hit‑testing or layout math, avoiding allocations in tight loops.
How Rect works
Rect holds four int fields: left, top, right, bottom. The right and bottom edges are exclusive, so a rectangle from (0,0) to (100,100) covers pixels 0‑99 on each axis. The class provides mutating methods such as offset(), inset(), union(), intersect(), and set() that modify the existing object instead of creating new ones.
Worked example: hit‑testing a custom view
public class TapView extends View {
private final Rect hitRect = new Rect(); // reused instance
public TapView(Context ctx) {
super(ctx);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Obtain the view's hit rectangle (the area that should receive touches)
getHitRect(hitRect); // fills hitRect with current bounds
// Check if the touch point lies inside the rectangle
if (hitRect.contains((int) ev.getX(), (int) ev.getY())) {
// Handle the tap
Log.d("TapView", "Tap inside bounds");
return true;
}
return super.onTouchEvent(ev);
}
}
Place this view in an activity layout (e.g., activity_main.xml) and run the app on any API level 21+. Touch inside the view produces the log line; touches outside do not.
Limits and common mistakes
- Treating right/bottom as inclusive leads to off‑by‑one errors when computing sizes or checking containment.
- Calling getHitRect() returns a reference to the view’s internal Rect; modifying it directly changes the view’s state. Always copy into a local Rect (as shown with the reusable hitRect field) before altering.
- Using Rect when sub‑pixel precision is needed (e.g., after a Matrix transformation) requires android.graphics.RectF instead.
- Allocating a new Rect inside onDraw or onTouchEvent each frame creates garbage; keep a private field and reuse it via set() or offset().
Practical verification
- Run the sample app and watch Logcat for "Tap inside bounds" when tapping the view.
- Enable Android Studio’s Profiler → Memory → Allocations and confirm that no Rect allocations appear in the onTouchEvent trace when the hitRect field is reused.
- Change the contains check to use
hitRect.right - 1andhitRect.bottom - 1and observe that touches on the bottom‑right pixel are missed, illustrating the exclusive‑edge rule.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.