Creating a UIView with a Tiled Background

Tiling a background texture is a pretty common thing to want to do. Instead of creating one large texture that fills the entire background, instead the goal is to take a smaller image, say 256×256, and repeat it horizontally and vertically to fill the background.

As far as I can tell, there’s no way to do this in Interface Builder. You can create a UIImageView to use as the background of a view, but the options for placing the image don’t include tiling.

Turns out tiling is just a special kind of colour.

[cc lang=”objc”]
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”corkboard” ofType:@”png”]];
self.backgroundColor = [UIColor colorWithPatternImage:image];

This loads an image called “corkboard.png” and sets it as a repeating pattern by using it as the view’s backgroundColor. The colour itself is a special kind of “colour” that’s actually the image itself, repeating over whatever space the color needs to fill.

Not a bad way to do it, but the odd location makes it a bit hard to discover.