开发者

Why I can't draw something on my UIView?

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?


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?


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);


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜