如何使用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;
答案 0 :(得分:8)
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;
答案 1 :(得分:7)
如果您将图层的fillColor
属性设置为nil
以外的其他属性或透明,则该图层将填充其路径。
如果您将图层的lineWidth
设置为大于零的数字,并将其strokeColor
设置为nil
以外的其他值或透明,则该图层将描绘其路径。
如果设置了所有这些属性,图层将填充和描边的路径。它在填充后绘制笔划。
图层的路径实际上必须包含一些区域才能填充任何内容。在您的帖子中,您可以设置如下路径:
UIBezierPath* path = [UIBezierPath bezierPath];
[path moveToPoint:self.lineStart];
[path addLineToPoint:self.lineEnd];
self.lineShape.path = path.CGPath;
该路径包含单个线段。它不包含任何区域,因此该层无需填充。
答案 2 :(得分:4)
在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)
}