2013-10-02 27 views
8

我正在製作一個圖像編輯器,它可以創建不同形狀的對象,如圓形,三角形和方形,這些對象也可以更新或刪除。所以我用CAShapeLayer來創建形狀對象。使用CAShapeLayer對象繪製與Bezierpath的線

現在我也想在圖像上畫一條線,也可以更新或刪除,所以我用了bezierpath和CAShapeLayer來創建線條,它工作的很好。但現在的問題是,當我想選擇任何現有的線時,可以在靠近線工具的地方選擇任何線,因爲CAShapeLayer也設置了從起點到終點的直線的填充區域。

我的問題是,如何使用CAShapeLayer創建沒有填充區域的行。

這裏是我創建一行代碼:

CAShapeLayer *line = [CAShapeLayer layer]; 
// Using bezierpath to make line 
UIBezierPath *linePath=[UIBezierPath bezierPath]; 

// Creating L with line 

[linePath moveToPoint:point1]; 
[linePath addToPoint:point2]; 
[linePath addToPoint:point3]; 
line.path=linePath.CGPath; 


// Configure the appearence of the line 
line.fillColor = Nil; 
line.opacity = 1.0; 
line.strokeColor = [UIColor whiteColor].CGColor; 

對此有何想法會非常感激。

+0

它的工作原理。可能你忘了添加圖層'''[self.view.layer addSublayer:line];''' – Shmidt

+0

我也添加了這一行,它創建的線條很好,但它也填充區域從起點到終點並考慮它作爲圖層的一部分。所以問題在於,每當我嘗試在線路層附近點擊時都會被選中。 –

+0

你應該使用'[linePath addLineToPoint:point2]'? –

回答

3

你可以試試這個。它的工作對我來說

CAShapeLayer *line = [CAShapeLayer layer]; 
    UIBezierPath *linePath=[UIBezierPath bezierPath]; 
    [linePath moveToPoint:CGPointMake(startx, starty)]; 
    [linePath addLineToPoint:CGPointMake(endx, endy)]; 
    line.lineWidth = 10.0; 
    line.path=linePath.CGPath; 
    line.fillColor = shapecolor.CGColor; 
    line.strokeColor = shapecolor.CGColor; 
    [[self.view layer] addSublayer:line]; 
+0

一定會檢查它並讓你知道。 –

+0

你是不是缺少[linePath stroke]? –

+0

這裏你不需要'[linePath stroke]',事實上,如果你這樣做的話你可能會得到上下文錯誤(除非你手動啓動一個上下文或者在'drawRect'中使用它) - 調用'stroke'使用Core圖形,但在這裏我們想使用Core Animation。 – DMan

0

我理解你,我遇到這個問題,也是試試這個:

GPathRef linePathRef = linePath.CGPath 
linePathRef = CGPathCreateCopyByStrokingPath(linePathRef, NULL, line.lineWidth, kCGLineCapRound, kCGLineJoinRound, 1); 
BOOL pathContainsPoint = CGPathContainsPoint(linePathRef, NULL, touchLocation, NO); 

if(pathContainsPoint){ 
    //Do something with the cashapelayer line... 
}else{ 
    //Do something here if needed... 
}