Monday, June 27, 2011

First working No NIB (NIBless) Drawing project using Quartz 2D

It took me a while after looking at different examples on the net and books - finally got it working. My first No NIB Drawing project using Quartz 2D.


The whole project code as below. Also learned from book to use "#define" to declare the MAX_X and MAX_Y values. May be if running the same code on different devices with different resolution (iPad, iPhone X, ...etc) or when user turned the device into different orientation can somehow work out the Max resolution and adjust it accordingly in the future?

And yes, that looks like a tic-tac-toe game... Still haven't work out how to do the other stuffs yet... ha ha... let's wait and see...



#import <UIKit/UIKit.h>

#define MAX_X 320.0
#define MAX_Y 480.0

@interface draw2D:UIView
@end

@implementation draw2D

- (id)initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
        
    /* Set the color */ 
    [[UIColor brownColor] set];
    /* Get the current graphics context */ 
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    /* Set the width for the line */ 
    CGContextSetLineWidth(currentContext, 5.0f);

    CGContextMoveToPoint(currentContext, 0, (MAX_Y/3));
    CGContextAddLineToPoint(currentContext, MAX_X, (MAX_Y/3));
    CGContextStrokePath(currentContext);

    CGContextMoveToPoint(currentContext, 0, (MAX_Y/3)*2);
    CGContextAddLineToPoint(currentContext, MAX_X, (MAX_Y/3)*2);
    CGContextStrokePath(currentContext);
    
    CGContextMoveToPoint(currentContext, (MAX_X/3), 0);
    CGContextAddLineToPoint(currentContext, (MAX_X/3), MAX_Y);
    CGContextStrokePath(currentContext);

    CGContextMoveToPoint(currentContext, (MAX_X/3)*2, 0);
    CGContextAddLineToPoint(currentContext, (MAX_X/3)*2, MAX_Y);
    CGContextStrokePath(currentContext);
}
@end

@interface TestBedAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    
}
@property (nonatomic, retain) UIWindow *window;

@end

@implementation TestBedAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];   
    
    draw2D *view = [[draw2D alloc] initWithFrame:CGRectMake(0.0, 0.0, MAX_X, MAX_Y)];
    
    [self.window addSubview:view];
    [view release];
    
    [self.window makeKeyAndVisible];
    
}

- (void)dealloc {
    [window release];
    [super dealloc];
}
@end

int main(int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
[pool release];
return retVal;
}

0 comments:

Post a Comment