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);
}
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"]]];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With