Based on Himanshu padia's response
If you want to "dynamically" combine more images (with the same aspect ratio) into one grid in Objective-C
I have used only two for this example on even/odd slots.
Formulas for equal inline and outline border:
// psx = (x - (n+1)*bs / n)
// psy = (y - (m+1)*bs / m)
Formulas for different inline and outline border
// psx = (x - (n-1)*bs + obs / n)
// psy = (y - (m-1)*bs + obs / m)
Explanation:
- psx, psy - piece size X and y
- x, y - original (piece) image size
- n, m - pieces slots in grid
- bs - border size
obs - outline border size
Why n+1 ?
Because for three pieces, you need 4 borders
|*|*|*|
Why n-1 ?
Because same as above, but excluding the first and last border
!*|*|*!
Code:
UIImage *image1 = [UIImage imageNamed:@"14x9blue"];
UIImage *image2 = [UIImage imageNamed:@"14x9red"];
// grid parameters
int k =0;
int m=3,n = 3;
int i=0, j=0;
CGFloat borderSize = 20.0f;
// equal border inline and outline
// the 1 is a multiplier for easier and more dynamic sizes
// 0*borderSize is inline border only, 1 is equal, 2 is double, etc.
CGFloat outlineBorder = 1*borderSize;
CGSize size = CGSizeMake(self.gridImageView.image.size.width, self.gridImageView.image.size.height);
CGRect gridImage = CGRectMake(0,0, size.width, size.height);
// piece size
// border inline and outline
// psx = (x - (n-1)*bs + obs / n)
// psy = (y - (m-1)*bs + obs / m)
CGFloat pieceSizeX = (size.width - (n-1)*borderSize - 2*outlineBorder) / n;
CGFloat pieceSizeY = (size.height - (m-1)*borderSize - 2*outlineBorder) / m;
UIGraphicsBeginImageContext(size);
// semi transparent fill
[[UIColor colorWithDisplayP3Red:240 green:250 blue:0 alpha:0.5] setFill];
UIRectFill(CGRectMake(0,0, size.width, size.height));
UIImage *currentImage;
for(i=0; i<m; i++) {
for (j=0; j<n; j++) {
if (k++%2) {
currentImage = image1;
} else {
currentImage = image2;
}
// 10-60 , 70-120, 130-180
[currentImage drawInRect:CGRectMake(
outlineBorder + (i)*borderSize + i*pieceSizeX,
outlineBorder + (j)*borderSize + j*pieceSizeY,
pieceSizeX,
pieceSizeY
)
];
}
}
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//set finalImage to IBOulet UIImageView
self.gridImageView.image = finalImage;