Skip to content

Instantly share code, notes, and snippets.

@jakeobrien
Created November 4, 2010 21:34
Show Gist options
  • Save jakeobrien/663234 to your computer and use it in GitHub Desktop.
Save jakeobrien/663234 to your computer and use it in GitHub Desktop.
Lays out a number of rects of given aspect ratio in a given frame.
- (void)drawGridWithFrame:(CGRect)rect containing:(int)numSquares squaresOfAspectRatio:(float)aspectRatio margin:(float)margin addToArray:(NSMutableArray *)array {
float totalArea = rect.size.width * rect.size.height;
float areaPerSquare = floorf(totalArea / numSquares);
float height = sqrtf(areaPerSquare/aspectRatio);
CGSize squareSize = CGSizeMake(aspectRatio * height, height);
int numPerRow = (int)floorf(rect.size.width / squareSize.width);
int numPerCol = (int)floorf(rect.size.height / squareSize.height);
if (numPerCol * numPerRow < numSquares) {
int numForWidthExp = (numPerRow + 1) * numPerCol;
int numForHeightExp = numPerRow * (numPerCol + 1);
if ((numForWidthExp >= numForHeightExp || numForHeightExp < numSquares) && numForWidthExp >= numSquares)
numPerRow++;
else if (numForHeightExp >= numSquares)
numPerCol++;
else {
numPerCol++;
numPerRow++;
}
}
float rectWidthMargin = 0.0;
float rectHeightMargin = 0.0;
float widthStretchFactor = (rect.size.width / (float)numPerRow) / squareSize.width;
if ((widthStretchFactor * squareSize.height) * numPerCol < rect.size.height) {
squareSize = CGSizeMake(squareSize.width * widthStretchFactor, squareSize.height * widthStretchFactor);
rectHeightMargin = (rect.size.height - (squareSize.height * numPerCol)) / 2.0;
} else {
float heightStretchFactor = (rect.size.height / (float)numPerCol) / squareSize.height;
squareSize = CGSizeMake(squareSize.width * heightStretchFactor, squareSize.height * heightStretchFactor);
rectWidthMargin = (rect.size.width - (squareSize.width * numPerRow)) / 2.0;
}
int index = 0;
for (int y = 0; y < numPerCol; y++) {
for (int x = 0; x < numPerRow; x++) {
ccColor4B color = (ccColor4B){rand() % 255, rand() % 255, rand() % 255, 255};
int width = (int)floorf(squareSize.width - (2.0 * margin));
int height = (int)floorf(squareSize.height - (2.0 * margin));
CCColorLayer *layer = [CCColorLayer layerWithColor:color width:width height:height];
float xPos = rect.origin.x + rectWidthMargin + (squareSize.width * x) + margin;
float yPos = (rect.origin.y + rect.size.height - + rectHeightMargin) - ((squareSize.height * (y + 1)) + margin);
layer.position = ccp(xPos, yPos);
[self addChild:layer];
if (nil != array)
[array addObject:layer];
index++;
if (index >= numSquares)
break;
}
if (index >= numSquares)
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment