2012-10-06 59 views
6

如何使用CAShapeLayer繪製具有邊框顏色,邊框寬度和填充顏色的線條?CAShapeLayer具有邊框和填充顏色和圓角

下面是我嘗試過,但它只有永遠的藍色......

self.lineShape.strokeColor = [UIColor blueColor].CGColor; 
self.lineShape.fillColor = [UIColor greenColor].CGColor; 
self.lineShape.lineWidth = 100; 
self.lineShape.lineCap = kCALineCapRound; 
self.lineShape.lineJoin = kCALineJoinRound; 
UIBezierPath* path = [UIBezierPath bezierPath]; 
[path moveToPoint:self.lineStart]; 
[path addLineToPoint:self.lineEnd]; 
self.lineShape.path = path.CGPath; 

回答

7
self.lineShapeBorder = [[CAShapeLayer alloc] init]; 
    self.lineShapeBorder.zPosition = 0.0f; 
    self.lineShapeBorder.strokeColor = [UIColor blueColor].CGColor; 
    self.lineShapeBorder.lineWidth = 25; 
    self.lineShapeBorder.lineCap = kCALineCapRound; 
    self.lineShapeBorder.lineJoin = kCALineJoinRound; 

    self.lineShapeFill = [[CAShapeLayer alloc] init]; 
    [self.lineShapeBorder addSublayer:self.lineShapeFill]; 
    self.lineShapeFill.zPosition = 0.0f; 
    self.lineShapeFill.strokeColor = [UIColor greenColor].CGColor; 
    self.lineShapeFill.lineWidth = 20.0f; 
    self.lineShapeFill.lineCap = kCALineCapRound; 
    self.lineShapeFill.lineJoin = kCALineJoinRound; 

// ... 

    UIBezierPath* path = [UIBezierPath bezierPath]; 
    [path moveToPoint:self.lineStart]; 
    [path addLineToPoint:self.lineEnd]; 
    self.lineShapeBorder.path = self.lineShapeFill.path = path.CGPath; 
+0

這是我的最終解決方案 – jjxtra

7

如果圖層的fillColor屬性設置爲nil或透明以外的內容,該層將填補其路徑。

如果你設置圖層的lineWidth到數大於零,並設置其strokeColornil或透明以外的內容,該層將行程中的路徑。

如果你設置的所有這些屬性,該層將填補行程中的路徑。它填充後繪製中風。

圖層的路徑必須實際上包含某個區域才能填充任何內容。在您的文章中,您設置如下路徑:

UIBezierPath* path = [UIBezierPath bezierPath]; 
[path moveToPoint:self.lineStart]; 
[path addLineToPoint:self.lineEnd]; 
self.lineShape.path = path.CGPath; 

該路徑包含單個線段。它沒有包含任何區域,所以圖層沒有任何可填寫的內容。

+0

我更新我的問題與我目前的代碼... – jjxtra

+0

@PsychoDad我已經更新了我的答案。 –

+0

所以我需要讓我的路徑成爲一個多邊形呢? – jjxtra

1

在Swift 3.擴展方法UIView

// Usage: 
self.btnGroup.roundCorner([.topRight, .bottomRight], radius: 4.0, borderColor: UIColor.red, borderWidth: 1.0) 

// Apply round corner and border. An extension method of UIView. 
public func roundCorner(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) { 
    let path = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) 

    let mask = CAShapeLayer() 
    mask.path = path.cgPath 
    self.layer.mask = mask 

    let borderPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) 
    let borderLayer = CAShapeLayer() 
    borderLayer.path = borderPath.cgPath 
    borderLayer.lineWidth = borderWidth 
    borderLayer.strokeColor = borderColor.cgColor 
    borderLayer.fillColor = UIColor.clear.cgColor 
    borderLayer.frame = self.bounds 
    self.layer.addSublayer(borderLayer) 
}