Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #179 Get center of a rectangle

Return the center c of the rectangle with coördinates(x1,y1,x2,y2)

import java.awt.Rectangle;
int w = x2 - x1, h = y2 - y1;
Rectangle r = new Rectangle(x1, y1, w, h);
double c[] = { r.getCenterX(), r.getCenterY() };
double[] c = {(x1+x2)/2,(y1+y2)/2};

c is double array that can be accessed using index 0 for x and 1 for y.

e.g. center[0]
import java.awt.geom.Rectangle2D;
double w = x2 - x1, h = y2 - y1;
Rectangle2D r = new Rectangle2D.Double(x1, y1, w, h);
double c[] = { r.getCenterX(), r.getCenterY() };
(defn c 
  "calculates the center c of a rectangle of coordinates(x1, y1, x2, y2)" 
  [x1 y1 x2 y2]
  {:x (/ (+ x1 x2) 2)
   :y (/ (+ y1 y2) 2)})

New implementation...
< >
Bart