我正在使用UIBezierPath让我的imageview有圆角,但我也想为imageview添加边框.请记住,顶部是uiimage,底部是标签.
let rectShape = CAShapeLayer() rectShape.bounds = myCell2.NewFeedImageView.frame rectShape.position = myCell2.NewFeedImageView.center rectShape.path = UIBezierPath(roundedRect: myCell2.NewFeedImageView.bounds,byRoundingCorners: .TopRight | .TopLeft,cornerRadii: CGSize(width: 25,height: 25)).CGPath myCell2.NewFeedImageView.layer.mask = rectShape
我想为此添加绿色边框,但我无法使用
myCell2.NewFeedImageView.layer.borderWidth = 8 myCell2.NewFeedImageView.layer.borderColor = UIColor.greenColor().CGColor
因为它会切断边框的左上角和右上角,如下图所示:
您可以重用UIBezierPath路径并向视图添加形状图层.以下是视图控制器内的示例.
原文链接:https://www.f2er.com/swift/320183.htmlclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Create a view with red background for demonstration let v = UIView(frame: CGRectMake(0,100,100)) v.center = view.center v.backgroundColor = UIColor.redColor() view.addSubview(v) // Add rounded corners let maskLayer = CAShapeLayer() maskLayer.frame = v.bounds maskLayer.path = UIBezierPath(roundedRect: v.bounds,height: 25)).CGPath v.layer.mask = maskLayer // Add border let borderLayer = CAShapeLayer() borderLayer.path = maskLayer.path // Reuse the Bezier path borderLayer.fillColor = UIColor.clearColor().CGColor borderLayer.strokeColor = UIColor.greenColor().CGColor borderLayer.lineWidth = 5 borderLayer.frame = v.bounds v.layer.addSublayer(borderLayer) } }
最终结果如下所示.
请注意,这仅在视图大小固定时按预期工作.当视图可以调整大小时,您需要创建自定义视图类并在layoutSubviews中调整图层大小.