Blog Archives

Using Patterns in Quartz2D

There’s not a ton of information out there about how to use patterns with the Quartz framework and drawing patterns, especially about combining it with UIColors ability to create colors with patterns.

You probably know about creating UIColors with pattern images:

UIColor *myPattern = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mypattern.png"]];

If you’re just filling in background colors with this, it works fine, but if you need to get down into the nitty gritty using CoreGraphics, you’ll need to do some more work. Here’s what you’ll need in the drawing code to make it all work:

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorRef color = [myPattern CGColor];
CGColorSpaceRef colorSpace = CGColorGetColorSpace(color);
CGContextSetFillColorSpace(ctx, colorSpace);
if (CGColorSpaceGetModel(colorSpace) == kCGColorSpaceModelPattern)
{
    CGFloat alpha = 1.0f;
    CGContextSetFillPattern(ctx, CGColorGetPattern(color), &alpha);
}
else
{ 
    CGContextSetFillColor(ctx, CGColorGetComponents(color));
}

This is the kind of code you might us drawRect: for a UIView. We first need to determine if we’re painting a color or an image which is determined by examining the color space in line 5.

If the color space model is not a pattern, we can set the fill color and simply move along. Otherwise we need to set the fill pattern. Using an alpha value for the components is described in the CGContext docs:

components
If the pattern is an uncolored (or a masking) pattern, pass an array of intensity values that specify the color to use when the pattern is painted. The number of array elements must equal the number of components in the base space of the fill pattern color space, plus an additional component for the alpha value.
If the pattern is a colored pattern, pass an alpha value.

Since we’re using a colored pattern image, we can simply use the alpha value.

That’s it! Hope this helps somebody out there!

EDIT: Sample project is now on GitHub

Also, here’s an easy online tool to create your own pattern: StripeGenerator

Advertisements