Elegant way to position two rectangles

I have a rectangle (called the target) and want to place another rectangle (called the satellite) alongside. The satellite has a position (top, bottom, left, right) that determines the placement edge relative to the target. It also has an alignment that (left, center, right for top and bottom position, top, middle and bottom for left and right position).

Example:

+----------+----------------------------+
|          |                            |
|  Target  | Satellite, Position=RIGHT, |
|          | Align=TOP                  |
|          |                            |
|          |----------------------------+
|          |
+----------+

I know the top left coordinates of the target and also its width and height. I also know the width and height of the satellite and want to calculate the top left coordinates of it. I could do that as a series of 12 if clauses, but maybe there is a more elegant, mathematical or algorithmic way to do it. Is there an alternative way to this:

# s = satellite, t = target
if pos == "top" && align == "left"
  s.x = t.x
  s.y = t.y - s.height
else if pos == "top" && align == "center"
  s.x = t.x + t.width / 2 - s.width / 2
  s.y = t.y - s.height
# etc, etc

Any good solutions in Ruby or JavaScript?

6
задан chiborg 16 April 2011 в 06:12
поделиться