Studie
Studie

Reputation: 799

How to draw a line programmatically?

The game tic tac toe seems to be a nice exercise for me.

I want to draw the tic tac toe grid first.
Interface Builder does not have a built in class for drawing lines.

Therefore my question is: Which class can I use to draw the lines of the grid programmatically?

Upvotes: 1

Views: 7332

Answers (4)

jobesu
jobesu

Reputation: 620

The easiest way to do that programmatically is to create a subclass of UIView and override the drawRect() method.

Here is an exemple of such a view's subclass named TTView:

#import "TTView.h"

@implementation TTView

- (void)drawRect:(CGRect)rect {
    int xStart = 10, yStart = 10;
    int gridSize = 300;

    UIBezierPath *topPath = [UIBezierPath bezierPath];
    // draw vertical lines
    for(int xId=1; xId<=2; xId++) {
        int x = xStart + xId * gridSize / 3;
        [topPath moveToPoint:CGPointMake(x, yStart)];
        [topPath addLineToPoint:CGPointMake(x, yStart+gridSize)];
    }

    // draw horizontal lines
    for(int yId=1; yId<=2; yId++) {
        int y = yStart + yId * gridSize / 3;
        [topPath moveToPoint:CGPointMake(xStart, y)];
        [topPath addLineToPoint:CGPointMake(xStart+gridSize, y)];
    }

    [[UIColor whiteColor] setStroke];

    [topPath stroke];
}

@end

Don't forget to create your view and add it to your UIViewController like that:

TTView *ttv = [[TTView alloc] initWithFrame:self.view.frame];
[self.view addSubview:ttv];
[ttv release];

Upvotes: 4

hotpaw2
hotpaw2

Reputation: 70673

You can create a UIView subclass, then instantiate that view's drawRect callback delegate to do any Core Graphics drawing (lines, etc.) desired.

If you wanted to do something strictly inside IB, you could use some UIViews as skinny as lines with their background colors set to the desired line color.

Upvotes: 2

fearmint
fearmint

Reputation: 5334

Sam Soffes writes SSToolkit described as

SSToolkit makes life easier. It is made up of various view controllers, views, and categories that I use in all of my apps. Feel free to fork the repo and make it better.

One of his classes is SSLineView to draw lines. I'm not sure how well it supports non-horizontal lines. Here's the .h and .m though it may have dependencies in the rest of SSToolkit.

Upvotes: 2

tobiasbayer
tobiasbayer

Reputation: 10369

Drawing in iOS can either be done with Core Graphics or Quartz 2D.

Upvotes: 2

Related Questions