Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangle - a mathematical problem

I have found something NOT funny with rectangles:

Lets say, given are values of left, top, right and bottom coordinates and all those coordinates are intended to be inclusive.

So, calculating the width goes like:

width = right - left + 1

So far, so logical. But!

A width of zero (which makes sense, sometimes) would have to be stored as:

right = left - 1

which makes problems, when it comes to the following operations:

  • Sorting the rectangle coordinates (to make it go left to right, top to bottom)
  • Looping

Ok, of course those things can be handled with extra code for the special case of Width == 0, but, seriously, is there no better solution, no standard pattern or best practice to handle this?

Edit:

For the time being I have abandoned the "sorting" of the coordinates in my code and replaced it with an assertion stating that the rectangle must be left -> right, up -> down, but seriously...

like image 901
StormianRootSolver Avatar asked Apr 25 '26 03:04

StormianRootSolver


2 Answers

To address this problem, most graphics libraries will draw rectangles from the left coordinate up to but not including the right coordinate. So if left=10 and right=20, then the ten pixels 10 through 19 will be drawn.

You can think of this as the pixel coordinate referring not to the lit-up portion, but the grid lines between pixels.

+---+---+---+
|   |   |   |
+---+---+---+
|   |   |   |
+---+---+---+
^   ^   ^   ^
0   1   2   3
like image 175
Greg Hewgill Avatar answered Apr 27 '26 17:04

Greg Hewgill


It's important to distinguish between coordinates and pixels. You can think of the coordinate system as being an invisible grid which runs between pixels. Thinking of coordinates this way if you define a rect as { 0, 3, 0, 5 }, then you get 3 pixels by 5 pixels as expected.

   |  |  |  |  |  |
0 -x--+--+--+--+--x-
   |  |  |  |  |  | 
1 -+--+--+--+--+--+-
   |  |  |  |  |  | <- pixels are rectangular areas between coordinate grid
2 -+--+--+--+--+--+-
   |  |  |  |  |  | 
3 -x--+--+--+--+--x-
   |  |  |  |  |  | 
   0  1  2  3  4  5
like image 23
Paul R Avatar answered Apr 27 '26 17:04

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!