为什么我无法在 UIView 上绘制内容?
这是我的主视图,我只是想让它画一些东西来测试,但我发现我的UI没有任何东西,这是代码:
- (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);
}
这是我在网上复制的示例代码。我认为代码是正确的,它没有任何错误,但什么也没有出现。或者……这段代码不应该粘贴到viewDidLoad上?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
viewDidLoad 没有上下文。您将需要创建一个图像上下文,进行绘图,生成图像,然后将其添加到视图中,如下所示:
编辑:
viewDidLoad 是一个 UIViewController 方法,而不是 UIView 方法。我假设这段代码在您的控制器中,我是对的吗?此外,viewDidLoad 仅在从 nib 加载视图后才会被调用。您是否使用了 nib(使用 Interface Builder 构建的 xib)或者以编程方式创建了视图?
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:
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?
要使用代码在视图上绘图,您需要重写
-drawRect:
而不是-viewDidLoad
。To draw on the view using your code, you need to override
-drawRect:
instead of-viewDidLoad
.