Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use CGContextDrawTiledImage to tile an image?

I want to be able to an UI object like a UIImageView and tile an image inside of it.

I have been able to use CGContextDrawTiledImage to update the background in the main window, but not an image view. I can do this if I modify the drawRect function inside the MainView class.

I feel I'm close, but still missing something. Can someone point me in the right direction?

- (void)drawRect:(CGRect)rect {

CGImageRef image = CGImageRetain(currentImage.CGImage);

CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);

CGContextRef uiContext = UIGraphicsGetCurrentContext();

CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));

CGContextDrawTiledImage(uiContext, imageRect, image);

}

like image 958
Chris Craft Avatar asked Mar 25 '09 01:03

Chris Craft


2 Answers

If you just want to tile an image in the view, change it to a normal UIView and tile the background with UIColor initWithPatternImage:

backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageWithContentsOfFile:[self bundlePath:@"some_tile_image.png" inDirectory:@"tiles"]]];
like image 92
Chris Blackwell Avatar answered Oct 02 '22 20:10

Chris Blackwell


Let's say you've got a CGImageRef for the image you want to tile called tileImage and a UIImageView called imageView. What you need to do is create a UIImage to assign to the image property of imageView. You can do that like this:

CGSize imageViewSize = imageView.bounds.size;
UIGraphicsBeginImageContext(imageViewSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
CGContextDrawTiledImage(imageContext, (CGRect){ CGPointZero, imageViewSize }, tileImage);
UIImage *finishedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

imageView.image = finishedImage;

This will create a bitmap image context of the desired size, tile the image into that context, get a UIImage out of the context, then assign it to the UIImageView. You can really put this code anywhere so long as the image view and tile image are loaded and ready to go.

like image 44
Alex Avatar answered Oct 02 '22 21:10

Alex