Basics of Drawing Using 2-D Graphics in iOS App

By Rajiv Ramnath

Using the built-in controls for defining your iOS app’s user interface is fun and easy. However, there’s a back-to-basics way to draw your user interface within a view using the iOS Quartz Graphics framework that provides you with 2-D graphics capability, as illustrated in the drawing of the Tic-Tac-Toe board.

To see an example of using 2-D graphics, refer to the Board class (files TTTBoard.m and .h). The interface file of the Board class is shown here:

@interface TTTBoard : UIView {
 …
}
 …
–d

Note that the drawRect method is overrode on the base View class, as shown here:

 // Drawing code
 - (void)drawRect:(CGRect)rect {
  int gridSize = TTTBOARDSIZE;
  UIBezierPath *drawingPath = [UIBezierPath bezierPath];
  // draw vertical lines
  for(int i=0; i <= 3; i++) {
   int x = TTTBOARDLOCATIONINVIEWX + [self getWidth]*i;
   [drawingPath moveToPoint:CGPointMake(x, TTTBOARDLOCATIONINVIEWY)];
   [drawingPath addLineToPoint:CGPointMake(x, TTTBOARDLOCATIONINVIEWY + gridSize)];
  }
  // draw horizontal lines
  for(int j = 0; j <= 3; j++) {
   int y = TTTBOARDLOCATIONINVIEWY + j * [self getHeight];
   [drawingPath moveToPoint:CGPointMake(TTTBOARDLOCATIONINVIEWX, y)];
   [drawingPath addLineToPoint:CGPointMake(TTTBOARDLOCATIONINVIEWX +
             gridSize,
             y)];
  }
  [[UIColor redColor] setStroke];
  [drawingPath stroke];
  // Draw the symbols
  float offsetX = 0;
  float offsetY = 0;
  for(int i = 0; i < GAMEGRIDSIZE; i++){
   for(int j = 0; j < GAMEGRIDSIZE; j++){
    UIImage *imageSelected =
     [[grid getValueAtLocation :i :j] getBitmapForSymbol];
    CGSize imageSize = [imageSelected size];
    offsetX = TTTBOARDLOCATIONINVIEWX +
       (int) (width * i + (width - imageSize.width)/2);
    offsetY = TTTBOARDLOCATIONINVIEWY +
       (int) (height * j + (height - imageSize.height)/2);
    [imageSelected drawAtPoint:CGPointMake(offsetX, offsetY)];
   }
  }
 }

The lines relevant to 2-D graphics drawing are extracted from the method, as shown here:

UIBezierPath *drawingPath = [UIBezierPath bezierPath];
 …
[drawingPath moveToPoint:CGPointMake(TTTBOARDLOCATIONINVIEWX, y)];
[drawingPath addLineToPoint:CGPointMake(TTTBOARDLOCATIONINVIEWX +
             gridSize,
             y)];
 …
[[UIColor redColor] setStroke];
[drawingPath stroke];
 …
[imageSelected drawAtPoint:CGPointMake(offsetX, offsetY)];

First, the UIBezierPath class lets you define a path consisting of line segments. The methods used here for adding line segments are moveToPoint and addLineToPoint. Next, the color of the pen is set using setStroke; then the line is rendered using the method stroke. Finally, the last statement — [imageSelected drawAtPoint:CGPointMake(offsetX, offsetY)]; — draws an image (in this case, any of the Tic-Tac-Toe symbols, including the Blank symbol) on the grid.