swift – UIBezierPath:如何在带圆角的视图周围添加边框?

前端之家收集整理的这篇文章主要介绍了swift – UIBezierPath:如何在带圆角的视图周围添加边框?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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边框和我当前的代码

您可以重用UIBezierPath路径并向视图添加形状图层.以下是视图控制器内的示例.
class 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中调整图层大小.

原文链接:https://www.f2er.com/swift/320183.html

猜你在找的Swift相关文章