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];
}
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)];
}
// 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