2015-06-19 79 views

回答

1

有两种常见的技术。

使用CAShapeLayer

创建UIBezierPath(替换任何你想要的坐标):

UIBezierPath *path = [UIBezierPath bezierPath]; 
[path moveToPoint:CGPointMake(10.0, 10.0)]; 
[path addLineToPoint:CGPointMake(100.0, 100.0)]; 

创建使用UIBezierPath一个CAShapeLayer:

CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 
shapeLayer.path = [path CGPath]; 
shapeLayer.strokeColor = [[UIColor blueColor] CGColor]; 
shapeLayer.lineWidth = 3.0; 
shapeLayer.fillColor = [[UIColor clearColor] CGColor]; 

添加一个CAShapeLayer到您的视图层:

[self.view.layer addSublayer:shapeLayer]; 

在以前的Xcode版本中,您必须手动将QuartzCore.framework添加到项目的“Link Binary with Libraries”中,然后将该头文件导入到.m文件中,但这不再必要(如果您有“Enable Modules “和”自动链接框架“构建设置打开)。

另一种方法是子类的UIView,然后使用CoreGraphics中的drawRect方法调用:

创建UIView子类,并定义吸引你的线路的drawRect:

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]); 
    CGContextSetLineWidth(context, 3.0); 
    CGContextMoveToPoint(context, 10.0, 10.0); 
    CGContextAddLineToPoint(context, 100.0, 100.0); 
    CGContextDrawPath(context, kCGPathStroke); 
} 

此后,您可以使用这种观点类作为您的NIB /故事板或视图的基类,或者你可以有你的视图控制器编程将其添加为一个子视图:

CustomView *view = [[CustomView alloc]  initWithFrame:self.view.bounds]; 
view.backgroundColor = [UIColor clearColor]; 

[self.view addSubview:view]; 
+0

非常感谢你......我创建了直线,并且我不了解 - (void)drawRect:(CGRect)矩形代码。你能解释一下这个代码吗? –

+0

关于“DrawRect”这是一种像你调用视图一样的方法,它从你的起点到终点创建了一行。每当你添加一个视图,绘制该类的rect,并在这里我自定义drawrect并画线CGContextMoveToPoint(context,10.0,10.0);到CGContextAddLineToPoint(context,100.0,100.0);并在我看来增加了这个观点。 –

相关问题