当我按下按钮时,如何在UIview中绘制线?(iOS)
我开始学习Xcode,当我按下按钮时,我不知道如何在视图中画一条线 我有这个密码当我按下按钮时,如何在UIview中绘制线?(iOS),ios,xcode,drawing,Ios,Xcode,Drawing,我开始学习Xcode,当我按下按钮时,我不知道如何在视图中画一条线 我有这个密码 - (void)drawRect:(CGRect)rect { CGContextRef con = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(con, 5); CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); CGFloat componen [] = {0.0, 0
- (void)drawRect:(CGRect)rect
{
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(con, 5);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componen [] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(space, componen);
CGContextSetStrokeColorWithColor(con, color);
CGContextMoveToPoint(con, 0, 0);
CGContextAddLineToPoint(con, 100, 100);
CGContextStrokePath(con);
CGColorSpaceRelease(space);
CGColorRelease(color);
}
这段代码在我启动应用程序时画了一条线,但我想在我用参数(x1、x2、y1、y2)按下按钮时启动这段代码。
我创建了这样一个函数
- (void)drawLine
{
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(con, 5);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componen [] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(space, componen);
CGContextSetStrokeColorWithColor(con, color);
CGContextMoveToPoint(con, x1, y1);
CGContextAddLineToPoint(con, x2, y2);
CGContextStrokePath(con);
CGColorSpaceRelease(space);
CGColorRelease(color);
}
但它不会画画
如何做到这一点?我为UIView添加一行内容非常简单
UILabel *line = [[UILabel alloc]init];
line.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
line.frame = CGRectMake(0, 0, 320, 1);
[self.view addSubview:line];
然后你们可以按下按钮来控制它的可见属性
你的问题可以吗?
-(void)drawRect:(CGRect)rect{}方法调用。 在加载视图之前,系统将调用它并绘制内容 因此,如果在视图加载后更改图形内容,则必须要求系统调用drawRect方法。因此,必须调用相关视图的setNeedsDisplay方法 [myView设置需要显示]
thanx定义您的
drawRect:
,以便它决定是否应该画一条线:
- (void)drawRect:(CGRect)rect {
if (self.drawLine) {
[self drawLineWithContext: UIGraphicsGetCurrentContext()];
self.drawLine = NO;
}
}
点击按钮后,让视图控制器设置视图参数,并告诉系统刷新视图:
- (IBAction)doDrawing:(id)sender {
self.drawView.drawLine = YES;
self.drawView.x1 = 20.0;
self.drawView.x2 = 200.0;
self.drawView.y1 = 10.0;
self.drawView.y2 = 350.0;
[self.drawView setNeedsDisplay];
}
你按按钮是什么意思?