Joehot200
Joehot200

Reputation: 1090

How to compute a rectangle coordinates from one point and its distances to the four edges

I would like to create a Rectangle that has got one side different than the other.

(All lines depicted are meant to be straight lines)

The normal rectangle is generated like new Rectangle(50 /*LocationX*/, 50 */LocationY*/, 50 /*SizeX*/, 100 /*SizeY*/);, and looks like this: enter image description here

However, I want a constructor like new Rectangle(50 /*LocationX*/, 50 */LocationY*/, 25 /*25 from the centre point for the red line*/, 30 /*30 from the centre point for the blue line*/, 50 /*50 from centre for green line*/, 100 /*100 from centre for yellow line*/);

In other words, I effectively want to keep the shape the same but move the centre point.

How can I do that?

Upvotes: 2

Views: 278

Answers (1)

Orace
Orace

Reputation: 8359

In java, rectangles are defined by upper-left corner coordinates, width and height.

If I understand your question here what describes your rectangle:

  • pointX, pointY coordinates of a point in the rectangle. Named the point.
  • distanceToTop distance from the point to the top of the rectangle (green line).
  • distanceToBottom distance from the point to the bottom of the rectangle (yellow line).
  • distanceToLeft distance from the point to the left of the rectangle (red line).
  • distanceToRight distance from the point to the right of the rectangle (blue line).

That given. The upper-left corner of the rectangle has for coordinates:

(pointX - distanceToLeft, pointY - distanceToTop)

And the whole rectangle has for size (width, height):

(distanceToLeft + distanceToRight, distanceToTop + distanceToBottom)

So your instance will be:

Rectangle r = new Rectangle(
    pointX - distanceToLeft,           // upper-left corner X
    pointY - distanceToTop,            // upper-left corner Y
    distanceToLeft + distanceToRight,  // width
    distanceToTop + distanceToBottom   // height
    );

Upvotes: 2

Related Questions