Logo

Programming-Idioms

  • PHP
  • Go
  • Java

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.

boolean b = x <= x2 && x >= x1 && y <= y2 && y >= y1;

Assume x1 <= x2 and y1 <= y2.
import java.awt.geom.Rectangle2D;
double w = x2 - x1, h = y2 - y1;
Rectangle2D r = new Rectangle2D.Double(x1, y1, w, h);
boolean b = r.contains(x, y);
import java.awt.Rectangle;
int w = x2 - x1, h = y2 - y1;
Rectangle r = new Rectangle(x1, y1, w, h);
boolean b = r.contains(x, y);
import "image"
p := image.Pt(x, y)
r := image.Rect(x1, y1, x2, y2)
b := p.In(r)

Points on the edge of the rectangle are considered as in 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

New implementation...
< >
Bart