views:

134

answers:

2

This is my Main View, I just want it draw some thing to test, but I find that my UI don't have any thing, here is the code:

- (void)viewDidLoad {
    [super viewDidLoad];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextMoveToPoint(context, 100.0f, 100.0f); 
    CGContextAddLineToPoint(context, 200.0f, 200.0f); 
    CGContextStrokePath(context);


}

This is the sample code I copied online. I assume the code is correct, it does not have any error, but nothing appear. Or... ... this code should not paste on viewDidLoad?

+1  A: 

viewDidLoad doesn't have a context. You will need to create an image context, do your drawing, produce an image, then add it to the view like so:

UIGraphicsBeginImageContext();
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0); 
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
CGContextMoveToPoint(context, 100.0f, 100.0f); 
CGContextAddLineToPoint(context, 200.0f, 200.0f); 
CGContextStrokePath(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
[imgView release];

Edit: viewDidLoad is a UIViewController method, not a UIView method. I assume this code is in your controller, am I correct? Also, viewDidLoad is only called after loading a view from a nib. Did you use a nib (xib built with Interface Builder) or did you create your view programmatically?

David Kanarek
+1  A: 

To draw on the view using your code, you need to override -drawRect: instead of -viewDidLoad.

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect]; // not necessary

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextMoveToPoint(context, 100.0f, 100.0f); 
    CGContextAddLineToPoint(context, 200.0f, 200.0f); 
    CGContextStrokePath(context);


}
KennyTM