swift – 剪切边框到子视图

我正在尝试制作两个UIViews的轮廓但是通过使用border属性我似乎无法达到我想要的效果.我得到左边的图像,我想要右边的那个:

《swift – 剪切边框到子视图》

这是我的代码:

    let main = UIView()
    main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
    main.backgroundColor = UIColor.clear
    self.view.addSubview(main)

    let v1 = UIView()
    v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
    v1.backgroundColor = UIColor.blue
    main.addSubview(v1)

    let v2 = UIView()
    v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
    v2.backgroundColor = UIColor.red
    main.addSubview(v2)

    main.clipsToBounds = true
    main.layer.borderColor = UIColor.black.cgColor
    main.layer.borderWidth = 3

最佳答案 您需要创建自定义形状的边框图层,如下所示:

let main = UIView()
main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
main.backgroundColor = UIColor.clear
self.view.addSubview(main)

let v1 = UIView()
v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
v1.backgroundColor = UIColor.blue
main.addSubview(v1)

let v2 = UIView()
v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
v2.backgroundColor = UIColor.red
main.addSubview(v2)


// Custom Shape Layer    
let maskLayer = CAShapeLayer()
maskLayer.frame = main.bounds

// Custom CGPath        
let resultPath = CGMutablePath()
resultPath.addPath(CGPath(rect: v1.frame, transform: nil))
resultPath.addPath(CGPath(rect: v2.frame, transform: nil))
maskLayer.path = resultPath

// Add border
let borderLayer = CAShapeLayer()
borderLayer.path = maskLayer.path
borderLayer.strokeColor = UIColor.black.cgColor
borderLayer.lineWidth = 5
borderLayer.frame = main.bounds
borderLayer.zPosition = -1
main.layer.addSublayer(borderLayer)
点赞