开发者

Why I can't draw something on my UIView?

开发者 https://www.devze.com 2022-12-20 13:44 出处:网络
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:

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

精彩评论

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

关注公众号