Tuesday, April 27, 2010

Creating custom view for iPhone

Currently I am trying to create simple game for iPhone. To create game first thing I needed to learn is to create custom view and custom drawing. So here I am putting down my learning in hope that it will help some one who started learning iPhone development.

I started with creating new window based project and named it CustomView.


Then I created new class named CustomView and derived it from UIView.


After creating class derived from UIVIew, we need to make sure that application's window add newly created class as its subview like shown in code below. 

- (void)applicationDidFinishLaunching:(UIApplication *)application {   

    CustomView *view = [[CustomView alloc] initWithFrame:window.frame];
   
    // Override point for customization after application launch
    [window addSubview:view];
    [window makeKeyAndVisible];
}

Then finally implement drawRect with custom drawing code. Here is my code with comment, in following code I am drawing a text, a rectangle , a circle and an Image.

- (void)drawRect:(CGRect)rect {
    // Drawing code
    //acquire graphics context
    CGContextRef ctxt = UIGraphicsGetCurrentContext();
   
    //set brush and set brush color to yellow
    CGContextSetFillColorWithColor(ctxt, [[UIColor yellowColor] CGColor]);
   
    //create string to draw
    NSString *hello = @"Hello World!";
    //create font to be used
    UIFont* font = [UIFont systemFontOfSize:20];
   
    //find horizontal center position for text
    int xLocation = ([self frame].size.width / 2) - ( [hello sizeWithFont:font].width /2 );
    [hello drawAtPoint:CGPointMake( xLocation, 100 ) withFont:[UIFont systemFontOfSize:16.0]];
   
    //draw rect
    CGContextFillRect(ctxt, CGRectMake(50, 50, 50, 50));
    //change brush color to green and draw circle
    CGContextSetFillColorWithColor(ctxt, [[UIColor greenColor] CGColor]);
    CGContextFillEllipseInRect(ctxt, CGRectMake(150, 150, 50, 50));
   
    //draw image
    UIImage *image = [UIImage imageNamed:@"red-ind.png"];
    [image drawAtPoint:CGPointMake( 100,200)];
}

So end result looks like following.

No comments:

Post a Comment