Logo

Programming-Idioms

  • Erlang
  • C

Idiom #178 Check if point is inside rectangle

Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.

int isInsideRect(double x1, double y1, double x2, double y2, double px, double py){
	return px >= x1 && px <= x2 && py >= y1 && py <= y2; 
}

Using C convention with 1 for true and 0 for false.

Assuming that x1 < x2 and y1 < y2
isInsideRect(X1, Y1, X2, Y2, PX, PY) when X1 =< PX andalso PX =< X2 andalso Y1 =< PY andalso PY =< Y2 -> true;
isInsideRect(_, _, _, _, _, _) -> false.
using System.Windows;
b = new Rect(new Point(x1, y1), new Point(x2, y2)).Contains(x, y);

There's an older System.Drawing.Rectangle class which has a similar API for this purpose if System.Windows is not available.

New implementation...
< >
Bart