Create a tiled UIImage from another image

221 views Asked by At

I have a source image and using this I want to create tiled images of various sizes.

I know I can achieve this on a view using colorWithPatternImage: but I want the output as a UIImage.

I tried doing this by first creating a UIView of the required size:

- (UIImage *)patternImageWithImage:(UIImage *)filteredImage andSize:(PatternImageSize)size; {

int numberOfRows;
int numberOfColoumns;

if (size == PatternImageSize3x3) {
    numberOfRows = 3;
    numberOfColoumns = 3;
}
else
{
    numberOfRows = 15;
    numberOfColoumns = 15;
}

float width = filteredImage.size.width;
float height = filteredImage.size.height;

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width * numberOfColoumns, height * numberOfRows)];
view.backgroundColor = [UIColor colorWithPatternImage:filteredImage];
[view.layer setOpaque:NO];

UIImage* patternImage = [self imageWithView:view];
return patternImage; }

And then creating a UIImage out of this view:

- (UIImage *)imageWithView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return img; }

This turned out to be a very memory intensive approach. Is there a more optimised way of achieving this result?

1

There are 1 answers

0
NSRover On BEST ANSWER

Ok, solved this by drawing the image in a CGContext:

UIGraphicsBeginImageContext(CGSizeMake(width * numberOfColoumns, height * numberOfRows));

for (int ii = 0; ii < numberOfRows; ii++) {
    for (int jj = 0; jj < numberOfColoumns; jj++) {
        float x = jj * width;
        float y = ii * height;
        [filteredImage drawInRect:CGRectMake(x, y, width, height)];
    }
}

UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();