UIColor with pattern image
A very handy method but not often referenced method in UIColor is
+ (UIColor *)colorWithPatternImage:(UIImage *)image
Very often, you find yourself having to add a background element to your UIViews. Such background are almost always a plain image with repetitive elements (such as a chess board for example). Having to insert a plain 640x960 (or more if using a scroll view) image to you view and project can be a complete waste of memory. In these cases, you might consider using a UIColor and simply instantiate it with a pattern image through colorWithPatternImage.
Assume you want to achieve the following effect in your UIView:
Instead of using a plain 640x960 UIImage, consider using the following (small!) image and line of code:
- (void)viewDidLoad
{
[super viewDidLoad] ;
UIColor *pattern = [UIColor colorWithPatternImage: [UIImage imageNamed: @"background.png"]] ;
[self.view setBackgroundColor: pattern] ;
}
This way, you only need to load in memory the small pattern image and the UIColor will do the job of extending it to fill the background for you. Also, you do not have to worry about positioning and resizing the background UIImageView to fit your view.
A small tip to bear in mind (from Apple documentation):
By default, the phase of the returned color is 0, which causes the top-left corner of the image to be aligned with the drawing origin. To change the phase, make the color the current color and then use the CGContextSetPatternPhase function to change the phase.