How to Create a Background Pattern

Beyond custom images and solid colors, a nice effect for a background is to use a repeating pattern. The code example that follows shows just how easy this is.

For this example, I started with the image below, a photo that I took in the Fall with my iPhone. I downloaded and cropped the image to 100w x 97h – this was a random size based what seemed to be a reasonable guess on how often the pattern should repeat. I saved the cropped image with the file name backgroundPattern.jpg and imported the file into my Xcode project.

To add the image as a pattern, I added the code below into the loadView method of a view controller:

- (void)loadView 
  // Setup the view
  [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] 
      applicationFrame]] autorelease]];
  // Create image from the desired pattern (jpg or png)
  UIImage *pattern = [UIImage imageNamed:@"backgroundPattern.jpg"];
  // Set the image as a background pattern
  [[self view] setBackgroundColor:[UIColor colorWithPatternImage:pattern]];

The screenshot below shows how this looks on the iPhone simulator.

  1. I have read that there is a nasty memory leak with colorWithPatternImage, an issue that Apple is aware of but has not yet addressed.

    The following code can be used to achieve the same effect:

    – (void)drawRect:(CGRect)rect {
    UIImage* backgroundPatternImage = [UIImage imageNamed:@”myRepeatingPattern.png”];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect tiledRect;
    tiledRect.origin = CGPointZero;
    tiledRect.size = backgroundPatternImage.size;

  2. Thanks for the Tutorial, but I need help with one step further:
    Have you tried the landscape mode?
    when the view controller switch to Landscape mode , the background image filled the view partially (since a UIImage has been used.)
    I tried UIImagesetContentMode.. but it’s not solved.

Comments are closed.