Pattern Drawing with CGPattern in iOS or Mac

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

If you are looking for help on how to stroke or fill up a pattern in iOS or Mac OS X, then You have landed at the right place.

NOTE: A reader of this post is assumed to have prior knowledge of custom drawing in iOS’s UIView, CGContext, and Quartz 2D basics

You can find the Code sample from Github

The Sample code demonstrates the following things:

  • Creation of 3 Different kinds of patterns using CGPattern
  • In the Sample, tap “Change Pattern” to switch to next pattern
  • Use the slider, to increase the size of pattern cell

pattern is an image, usually small, used for filling regions by tiling, that is, by placing copies of the pattern side by side like ceramic tiles. Here we see how we can achieve pattern filling in iOS or Mac using CGPattern.

A step by step explanation on usage of CGPatterns

Quartz draw the patterns using cell based drawing technique, where it would provide us the option to draw a single pattern cell in a context, and uses the context to tile across the remaining area evenly.

STEP 1 : Create a CGPattern instance as below

//Pattern Callback methods

// drawPatternCell – callback to draw a single cell

//PatternReleaseInfoCallback – invoked when a pattern is released

CGPatternCallbacks callBack;

callBack.drawPattern = &drawPatternCell;

callBack.releaseInfo = &PatternReleaseInfoCallback;

callBack.version = 0;

 

// param1 – &patters_types[patternCount] – a context info, here which defines which pattern to be drawn


// param2 – rect of a single pattern cell

 

// param3 – transformation matrix

 

// offsetX – a offset or horizontal gap between each cell.. minimum should be width of the cell

 

// offsetY – a offset of vertical gap between each cell. minimum should be heigh of the cell

 

// Style of – how the pattern cell are to be placed where are drawn on a region bigger than the single pattern cell

 

// shouldColor –   a pattern can also be used as a mask, where the color is applied during the actual context where the pattern is drawn. So, literally you have to say true, if the pattern cell can chose its color, or no if the color at its main context is to be chosen

 

// callback – 2 callbacks encapsulated in a struct CGPatterCallbacks

 

_patterns[patternCount] = CGPatternCreate(&patters_types[patternCount], CGRectMake(0.0, 0.0, PATTERN_CELL_WIDTH, PATTERN_CELL_HEIGHT), CGAffineTransformIdentity, PATTERN_CELL_WIDTH, PATTERN_CELL_HEIGHT, kCGPatternTilingConstantSpacing, true, &callBack);

 

 

STEP 2:  (Important) define the drawPattern callback as below. This is the place where you are allowed to draw a single cell of a pattern. The drawing technique of pattern cell is same as one would draw in View’s drawRect method or drawing with any CGBitmapContext.

 

Pattern 1 – Chequered flag –

Chequered Flag Pattern

//Chequered Flag

//Fill the entire background with white color

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

CGContextFillRect(context, CGRectMake(0.0, 0.0, cellWidth, cellHeight));

 

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);

//Fill the top left quarter of the cell with black

CGContextFillRect(context, CGRectMake(0.0, 0.0, cellWidth/2.0, cellHeight/2.0));

 

//Fill the bottom right quarter of the cell with black

CGContextFillRect(context, CGRectMake(cellWidth/2.0, cellHeight/2.0, cellWidth/2.0, cellHeight/2.0));

 

Pattern 2

pattern_2

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

//http://www.kitchenbeforeandafter.com/wp-content/uploads/2009/05/kitchen-backsplash-tile-patterns2-300×216.gif

//       /

//     /

//  _ /

//   |_|

//  /  

// /    

///      

 

 

//stroke middle square

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

CGContextFillRect(context, CGRectMake(0.0, 0.0, cellWidth, cellHeight));

 

 

//stroke diagonal

CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

CGPoint points [] = {{0.0,0.0}, {cellWidth,cellHeight }, {cellWidth,0.0}, {0.0,cellHeight}};

CGContextStrokeLineSegments(context, points, 4);

 

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);

int num_of_parts = 8;

float partWitdth = cellWidth / num_of_parts;

CGRect middleSpot = CGRectMake(partWitdth * 3, partWitdth*3, 2* partWitdth, 2*partWitdth);

 

CGContextFillRect(context, middleSpot);


Pattern 3

Circular_pattern

The Elements involve in this pattern are a circle drawn with various transformations

  • Circle
  • Semi-Circle
    • Circle shifted towards left by half the width of the cell
    • Circle shifted towards right by half the width of the cell
    • Circle shifted towards top by half the height of the cell
    • Circle shifted towards bottom by half the height of the cell
  • Arc
    • Circle shifted towards left & top by half the width and half the height of the cell respectively
    • Circle shifted towards left & bottom by half the width and half the height of the cell respectively
    • Circle shifted towards right & top by half the width and half the height of the cell respectively
    • Circle shifted towards right & bottom by half the width and half the height of the cell respectively

You can clone a copy of this Sample project from GitHub

STEP 3: Applying the Pattern.

Finally we would be applying the pattern in drawRect method of BBQuartzView in this sample.

// Drawing code

float alpha = 1;

 

//choose the pattern to be filled based on the currentPattern selected

CGContextRef context = UIGraphicsGetCurrentContext();

CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern (NULL);// 6

CGContextSetFillColorSpace (context, patternSpace);// 7

CGColorSpaceRelease (patternSpace);

 

//set the pattern as the Current Context’s fill pattern

 

//we dont need to set any color, as the pattern cell itself has chosen its own color

CGContextSetFillPattern(context, _patterns[_currentPattern],   &alpha);


//We would be filling the entire portion of this view

CGContextFillRect(context, [self bounds]);

  • Choose the pattern that needs to be applied. In this sample, the pattern is chosen based on the _currentPattern variable value (0- Chequered pattern, 1- Pattern2, 3- Pattern3)
  • Patterns are created at the time of initializing the view. In sample, it is in initWithCoder method of BBQuartzView
  • The drawPattern callback is invoked only when the pattern is all set to be drawn. In my case, it is invoked when CGContextFillRect in the above drawing code snippet. You can use this pattern to fill any shape. The selected pattern would also be reflected while using CGContext drawing API like, CGContextFill variants, CGContextFillPath variants
  • The drawPattern Callback is called only once in its lifetime and for subsequent drawing, the pattern cell buffer would be re-used. So resize the single pattern cell, the patterns are re-created

Here is are the pics how the patterns would look like(captured from sample code).

patterns.png

 

You can clone a copy of this Sample project from GitHub

Hope, you find this piece of info useful. Fill in your comments or queries in below comment’s section. Waiting for you comments.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *