我想要这样的用户界面
我希望此视图上有圆角和阴影。
这是我在Xib中的View层次结构:
-Content View
- Shadow View
- Container View
- Left View
- Concave View
- Action View
这是实现当前用户界面的代码段:
用于凹陷路径:
let couponPath = UIBezierPath()
let zeroPoint = CGPoint.zero
couponPath.move(to: zeroPoint)
couponPath.addLine(to: CGPoint(x: leftView.frame.width, y: zeroPoint.y))
let radius = concaveView.frame.width / 2
let centerX = zeroPoint.x + leftView.frame.width + radius
couponPath.addArc(withCenter: CGPoint(x: centerX, y: zeroPoint.y), radius: radius, startAngle: CGFloat.pi, endAngle: 0, clockwise: false)
couponPath.addLine(to: CGPoint(x: containerView.frame.width, y: zeroPoint.y))
couponPath.addLine(to: CGPoint(x: containerView.frame.width, y: containerView.frame.height))
couponPath.addArc(withCenter: CGPoint(x: leftView.frame.width + radius, y: containerView.frame.height), radius: radius, startAngle: CGFloat.pi * 0, endAngle: CGFloat.pi, clockwise: false)
couponPath.addLine(to: CGPoint(x: zeroPoint.x, y: containerView.frame.height))
couponPath.close()
然后我创建CALayer
,该路径为couponPath
。
let shapeLayer = CAShapeLayer()
shapeLayer.path = couponPath.cgPath
然后将其蒙版到我的containerView中:
self.containerView.layer.mask = shapeLayer
我尝试使用此代码添加阴影。
let shadowLayer = CAShapeLayer()
shadowLayer.frame = containerView.frame
shadowLayer.path = shapeLayer.path
shadowLayer.shadowOpacity = 0.5
shadowLayer.shadowRadius = 5
shadowLayer.masksToBounds = false
shadowLayer.shadowOffset = CGSize(width: 0, height: 20)
self.shadowView.layer.addSublayer(shadowLayer)
如何在容器视图的半径上添加另一个遮罩? 还有没有更好的方法添加阴影而不是使用新的View(ShadowView)并在其上应用阴影?
这是我的xib,并查看Gist
谢谢。
答案 0 :(得分:0)
这应该有助于您处理阴影和圆角。您可以设置shadowView图层,而不是添加子图层。
class RoundedCornerView: UIView {
var shadowView: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
// Set the layer of the main view to have rounded corners
layer.cornerRadius = 12.0
layer.masksToBounds = true
// Create a shadow view and its mask
shadowView = UIView(frame: bounds)
addSubview(shadowView!)
sendSubviewToBack(shadowView!)
shadowView?.layer.shadowColor = UIColor.black.cgColor
shadowView?.layer.shadowOffset = 4.0
shadowView?.layer.shadowOpacity = 0.4
shadowView?.layer.shadowRadius = 12.0
shadowView?.layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath
shadowView?.layer.masksToBounds = false
shadowView?.clipsToBounds = false
}
}
答案 1 :(得分:0)
我最终使用了this answer on stackoverflow并自定义了阴影和角落。