对于围绕特定角落的SO有很多答案。我遇到的问题是我试图将按钮角对齐到下方视图的圆角。请看图像。黄色视图在4个角落是圆形的。我试图让关闭按钮在右上方圆形以与黄色视图的圆角对齐。我使用了下面的Swift 3代码,但按钮保持正方形。任何人都可以指出缺少什么吗?
viewRaised是黄色视图。
非常感谢!
let path = UIBezierPath(roundedRect: btnCancel.layer.bounds, byRoundingCorners:[.topRight, .bottomLeft], cornerRadii: CGSize(width: 10, height: 10))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
btnCancel.layer.mask = maskLayer
btnCancel.layer.masksToBounds = true
self.viewRaised.layer.cornerRadius = 10
self.viewRaised.layer.masksToBounds = false
self.viewRaised.layer.shadowOffset = CGSize(width: 5, height: 10);
self.viewRaised.layer.shadowRadius = 10;
self.viewRaised.layer.shadowOpacity = 0.5;
更新
有趣的是,相同的代码似乎正在起作用,但仅适用于左上角。见第二张图片。
self.viewRaised.layer.cornerRadius = 10
self.viewRaised.layer.masksToBounds = false
self.viewRaised.layer.shadowOffset = CGSize(width: 5, height: 10);
self.viewRaised.layer.shadowRadius = 10;
self.viewRaised.layer.shadowOpacity = 0.5;
let path = UIBezierPath(roundedRect: btnCancel.layer.bounds, byRoundingCorners:[.allCorners], cornerRadii: CGSize(width: 10, height: 10))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
btnCancel.layer.mask = maskLayer
这非常令人困惑。我正在使用XCode版本8.0 beta 6(8S201h)
答案 0 :(得分:2)
btnCancel.layer.mask
应设置为黄色视图。btnCancel
作为黄色视图的父级的子图层。 示例(Swift 3.x):
let yellowView = UIView(frame: CGRectMake(20.0, 20.0, 200.0, 200.0))
yellowView.backgroundColor = UIColor.yellowColor()
yellowView.layer.borderColor = UIColor.clearColor().CGColor
yellowView.layer.borderWidth = 1.0
yellowView.layer.cornerRadius = 10.0
self.view.addSubview(yellowView) // Add yellowView to self's main view
let btnCancel = UIView(frame: CGRectMake(20.0, 20.0, 45.0, 45.0))
btnCancel.backgroundColor = UIColor.redColor()
btnCancel.layer.mask = yellowView.layer // Set btnCancel.layer.mask to yellowView.layer
self.view.addSubview(btnCancel) // Add btnCancel to self's main view, NOT yellowView
注意:强>
您无需启用
clipsToBounds
,因为您正在设置遮罩层。您也不需要为掩码创建新的
CAShapeLayer
。使用yellowView
的图层作为蒙版。
Swift 4.x:
let yellowView = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 200.0, height: 200.0))
yellowView.backgroundColor = .yellow
yellowView.layer.borderColor = UIColor.clear.cgColor
yellowView.layer.borderWidth = 1.0
yellowView.layer.cornerRadius = 10.0
self.view.addSubview(yellowView) // Add yellowView to self's main view
let btnCancel = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 45.0, height: 45.0))
btnCancel.backgroundColor = .red
btnCancel.layer.mask = yellowView.layer // Set btnCancel.layer.mask to yellowView.layer
self.view.addSubview(btnCancel) // Add btnCancel to self's main view, NOT yellowView
答案 1 :(得分:0)
我需要做的就是删除所有这一切。但是如果我只删除粗体线就行了。但由于“取消按钮”是黄色视图的子视图,所以其余行不需要一次。
let path = UIBezierPath(roundedRect: btnCancel.layer.bounds, byRoundingCorners:[.topRight, .bottomLeft], cornerRadii: CGSize(width: 10, height: 10))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
btnCancel.layer.mask = maskLayer
btnCancel.layer.masksToBounds = true