如何使用 CGContextRef 使 View 类中的 Drawing 方法工作?
我在 View 类中有这两个方法。当视图初始化时,drawRect 方法总是被调用。但我无法使用 drawLine 方法。当它被调用时它不会做任何事情。我应该处理 cgimagecontext 或类似的东西吗?请帮忙!
- (void)drawRect:(CGRect)rect {
// Drawing code
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 480);
CGContextStrokePath(contextRef);
}
-(void)drawLine:(CGPoint)from to:(CGPoint) to {
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 128, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 50);
CGContextStrokePath(contextRef);
}
I have these 2 methods in the View class. the drawRect method always gets called when the view is initalized. But i can't get the drawLine method to work. It doesn't do anything when it gets called. Am i supposed to deal with cgimagecontext or something like that? please help!!
- (void)drawRect:(CGRect)rect {
// Drawing code
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 480);
CGContextStrokePath(contextRef);
}
-(void)drawLine:(CGPoint)from to:(CGPoint) to {
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 128, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 50);
CGContextStrokePath(contextRef);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否从 -drawRect 中调用 -drawLine ?您需要在您的drawRect方法中完成视图中的所有绘制。如果您从其他地方调用 -drawLine,它将不起作用。
Are you calling -drawLine from within -drawRect? You need to do all drawing in a view within your drawRect method. If you're calling -drawLine from somewhere else, it won't work.
您只能在drawrect 中进行绘图。如果您想通过drawLine方法绘制自定义线条,请用变量替换drawrect中的硬编码点。然后,您可以在drawLine方法中设置这些变量,最后调用[self setNeedsDisplay]。
You can only do drawing in drawrect. If you want to draw custom lines via your drawLine method, replace the hard-coded points in drawrect with variables. You can then set these variables in your drawLine method and finally call [self setNeedsDisplay].