Custom Draw

I'm gonna post some boilerplates so I don't have to look it up again.

UIKit's way to draw is to use Quartz.

Basic drawing requires 3 steps:

  • overload the drawRect method of the UIView class
  • wrap the custom view in a view controller
  • add this controlled view in a container, e.g. the window.

1. overload drawRect

Create a custom UIView class

ScoreView.h

1
2
3
4
5
6
#import <UIKit/UIKit.h>

@interface ScoreView : UIView {
}

@end

ScoreView.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import "ScoreView.h"

@implementation ScoreView

- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef _context = UIGraphicsGetCurrentContext();
CGRect _rect = CGRectMake(40, 40, 240, 120);

CGContextSetRGBFillColor(_context, 0.0, 0.0, 1.0, 1.0);
CGContextFillRect(_context, _rect);
}

@end

2. wrap in a controller

KonViewController.h

1
2
3
4
5
6
7
8
9
10
11
#import <UIKit/UIKit.h>

@class ScoreView;

@interface KonViewController : UIViewController {
ScoreView *scoreView;
}

@property (nonatomic, assign) ScoreView *scoreView;

@end

KonViewController.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#import "KonViewController.h"
#import "ScoreView.h"

@implementation KonViewController

@synthesize scoreView;

- (void)loadView {
self.wantsFullScreenLayout = YES;

ScoreView *view = [[ScoreView alloc]
initWithFrame:[UIScreen mainScreen].applicationFrame];
self.view = view;
self.scoreView = view;

[view release];
}

@end

3. attach to window

KonAppDelegate.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#import <UIKit/UIKit.h>

@class KonViewController;

@interface KonAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
KonViewController *konViewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) KonViewController *konViewController;

@end

KonAppDelegate.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#import "KonAppDelegate.h"
#import "KonViewController.h"

@implementation KonAppDelegate

@synthesize window;
@synthesize konViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.konViewController = [[[KonViewController alloc] init] autorelease];

[window addSubview:konViewController.view];
[window makeKeyAndVisible];
}


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

@end

Those are the only 6 files I needed to make the app compile, besides the never changing main.m.

I did find some problem with UIKit though, in particular, errors could pass on silently. I had to guess very hard what the problem could be. Anyway, need to find a better debugging method.

blog comments powered by Disqus