2015-06-19 78 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);並在我看來增加了這個觀點。 –

相關問題