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; 

如果将图层的fillColor属性设置为nil或transparent之外的其他属性,则图层将填充其路径。

如果将图层的lineWidth设置为大于零的数字,并将其strokeColor设置为除nil或透明以外的其他值,则图层将strokeColor其路径。

如果设置了所有这些属性,则图层将填充描边其路径。 它在填充后绘制笔划。

图层的路径实际上必须包含一些区域才能填充任何区域。 在您的post中,您设置如下路径:

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

该路径包含单个线段。 它不包含任何区域,因此该层无需填充。

  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; 

在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) }