Search code examples
algorithmmathlanguage-agnosticgeometry

How to align rectangles with different width horizontally to center, but keeping the anchor point at the centre of each rectangle?


For example, if I have 2 rectangles, the anchor point is in the centre of the rectangle, one the width is 6 (Red), another is 2 (blue), I want to align them horizontally to the centre like this:

enter image description here

So that the position(also the centre and anchor point) of whole structure is at the origin, the red rectangle should be placed at (-1,0), and the blue rectangle should be placed at (3,0).

This example can be solved by graph and divided into 1 unit segments, but how about if I have arbitrary numbers of rectangles with different width?

enter image description here

How to find the position of each rectangle which the anchor point of each rectangle is at the centre?


Solution

  • Sum the widths of all the rectangles and then divide by 2. This is the distance from the left side of the left-most rectangle to center.

    Then for each rectangle, compute the distance from the left side of the left-most rectangle to the rectangle's center point. Subtract this from the first number to find the offset of the rectangle's center point from the center.

    Pseudo-code:

    Find distance from the left side of the left-most rectangle to center:

    int i;
    float sum = 0;
    for(i = 0; i < rectangle_count; i++)
        sum += rectangles[i].width;
    centerpoint = sum / 2.0;
    

    Compute offset of each rectangle from center:

    sum = 0.0;
    for(i = 0; i < rectangle_count; i++)
    {
        // compute offset for this rectangle relative to center:
        rectangles[i].offset = (sum + (rectangles[i].width / 2.0)) - centerpoint;
    
        sum += rectangles[i].width;
    }