2013-08-02 21 views
11

這裏的示例代碼:爲什麼CAShapeLayer的筆畫延伸出框架?

//Called by VC: 

HICircleView *circleView = [[HICircleView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

// init of circle view 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     CAShapeLayer *borderLayer = [CAShapeLayer layer]; 
     borderLayer.fillColor = [UIColor whiteColor].CGColor; 
     borderLayer.path = [UIBezierPath bezierPathWithOvalInRect:self.frame].CGPath; 
     borderLayer.strokeColor = [[UIColor redColor] CGColor]; 
     borderLayer.lineWidth = 5; 
     [self.layer addSublayer:borderLayer]; 
    } 
    return self; 
} 

enter image description here

OK,感謝您的回答。向移位i:

CGRect rect = CGRectMake(3, 3, self.frame.size.width, self.frame.size.height); 
borderLayer.path = [UIBezierPath bezierPathWithOvalInRect:rect].CGPath; 

並製作了6條線寬。

回答

11

設置lineWidth繪製一條線,其中實際路徑恰好在繪製線的中間。

如果您希望繪製的線與某些東西對齊,您將不得不將路徑移動lineWidth的一半。

您可以在UIBezierPath上使用- (void)applyTransform:(CGAffineTransform)transform來移動路徑並應用轉換轉換。

如果您想要將某個繪製的路徑包含在某個區域中,則移動該路徑不會有幫助。在這種情況下,只需創建一條較小的路徑如果要繪製寬度爲5的100ptx100pt矩形,則必須在95pt * 95pt矩形(任一側上的2.5pt空間)中繪製一條路徑。

+0

THanks。你能解釋如何改變線路嗎?沒關係。得到它了。 –

+0

我更新了答案,希望現在有點清楚。 – Sebastian

5

你寧願選擇你的視圖的邊界屬性進行計算。如果原點大於(0,0),Frame屬性將無法正常工作。您可以使用CGRectInsets來調整您的圓的矩形,而不是執行變換計算。這會自動將矩形放置在原始矩形的中心。

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     CAShapeLayer *borderLayer = [CAShapeLayer layer]; 
     borderLayer.fillColor = [UIColor whiteColor].CGColor; 
     CGFloat lineWidth = 5; 
     CGRect rect = CGRectInset(self.bounds, lineWidth/2, lineWidth/2); 
     borderLayer.path = [UIBezierPath bezierPathWithOvalInRect:rect].CGPath; 
     borderLayer.strokeColor = [[UIColor redColor] CGColor]; 
     borderLayer.lineWidth = lineWidth; 
     [self.layer addSublayer:borderLayer]; 
    } 
    return self; 
} 
+0

感謝CGRectInset小費,這是我在Swift 3中結束的: 'let delta = type(of:self).StrokeLineWidth/2.0' 'let rect = contentView.bounds.insetBy(dx: delta,dy:delta)' – Lucien