将边框剪切到子视图 [英] Clipping borders to subviews
本文介绍了将边框剪切到子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图绘制两个UIView的轮廓,但是通过使用border属性,我似乎无法实现我想要的.我的图片在左侧,我想要的在右侧:
I'm trying to make a contour of two UIViews but by using the border property I can't seem to achieve what I want. I'm getting the image on the left, and I want the one on the right:
这是我的代码:
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
推荐答案
您需要像这样创建自定义形状的边框层:
You need to create custom shaped border layer like so:
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)
这篇关于将边框剪切到子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文