A: 

Draw blue and pink rectangles separately and draw one last blue rectangle :) (or don't draw one last pink one)

Eugene
+2  A: 

Given n boxes of width w and spacing s, the total length will be:

l = n × w + (n-1) × s

You know all the variables. The same formula can be used to place an arbitrary box. From your diagram, we can see that the length is the same as the right-edge coordinate of the final box. So you can just use n from 1 through whatever to find the right-edge of all your boxes. Finding left edge from that is trivial: subtract w, add 1 (as a box from 80 to 80 is 1px wide).

Note that n counts from 1, not 0. You can change the formula, of course, to count from 0.

derobert
+1  A: 

I would do something like this:

CGFloat barStartX = 96;
CGFloat barStartY = 64.0;
CGFloat barWidth = 128;
CGFloat barHeight = 64;

...

int numSegments = 8;      // number of segments
CGFloat spacing = 8;      // spacing between segments

CGFloat segmentWidth = (barWidth - spacing*(numSegments - 1)) / numSegments;

CGRect segmentRect = CGRectMake(barStartX, barStartY, segmentWidth, barHeight);
for (int segmentNumber = 0; segmentNumber < numSegments; segmentNumber++)
{
    segmentRect.origin.x = segmentNumber*(segmentWidth + spacing);
    CGContextFillRect(context, segmentRect);
}

I like to define the rectangle outside of the loop, and then, in the loop, update only the properties of the rectangle that are actually changing. In this case, it is only the x coordinate that changes every time, so the loop becomes pretty simple.

e.James
I got your code and increased barWidth to 128, because it's now used as total width instead of single box width. 'segment' should be 'segmentRect'. segmentRect.x should be segmentRect.origin.x. Then it works.
willc2
@willc2: Glad to hear you got it working, and thank you for pointing out my errors. I have changed the code to fix them. :)
e.James
+4  A: 

I think that despite your effort, this question is a bit unclear. Here's my attempt, though.

The equation that you describes in the title is:

N*x + (N-1)*S = L

Solving that for x gives us the width necessarry for each box:

x = (L - (N-1)*S) / N

This would result in code similar to something like this:

CGContextRef context = UIGraphicsGetCurrentContext(); 

int barSegments = 8;

CGFloat barStartX = 96;
CGFloat barStartY = 64.0;
CGFloat barTotalWidth = 196.0;

CGFloat barHeight = 64;
CGFloat barGutter = 8;
CGFloat barWidth = (barTotalWidth - (barSegments-1)*barGutter) / barSegments;

for (int segmentNumber = 0; segmentNumber < barSegments; ++segmentNumber) {

        // get the box rect
        CGRect segment = CGRectMake(barStartX + ((barWidth + barGutter) * segmentNumber), barStartY , barWidth, barHeight);

        // plot box
        CGContextFillRect(context, segment);
}
Emil H
This is exactly the kind of elegant solution that I knew was out there, thank you.
willc2