如何设置角半径,边框和阴影的UIView蒙版?

时间:2018-04-13 08:42:18

标签: ios swift

我想要实现的目标是将UIViewshadowbordercornerRadius一起应用。

到目前为止,我可以设置maskcornerRadiusborder。问题在于尝试设置shadow

这是我目前的代码

let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))

let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask

let frameLayer = CAShapeLayer()
frameLayer.path = path.cgPath
frameLayer.lineWidth = width
frameLayer.strokeColor = color.cgColor
frameLayer.fillColor = nil

layer.addSublayer(frameLayer)

问题是如果我尝试将shadow设置为frameLayer或layer,我没有得到理想的结果。它会被蒙面修剪掉。有没有办法实现这个,除了使用下一行代码?

layer.cornerRadius = 5
layer.borderColor = color.cgColor
layer.borderWidth = width
layer.shadowColor = shadowColor.cgColor
layer.shadowOpacity = opacity
layer.shadowRadius = radius
layer.shadowOffset = offset
clipsToBounds = true

两个片段都打算在UIView子类中使用,所以如果有人可以帮我解决这个问题,我会非常感激。感谢

如果还有其他需要或不清楚的地方请告诉我

1 个答案:

答案 0 :(得分:1)

嘿,半小时后我设法找到解决自己问题的方法:

let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))

let frameLayer = CAShapeLayer()
frameLayer.path = path.cgPath
frameLayer.shadowPath = path.cgPath

frameLayer.lineWidth = borderWidth
frameLayer.strokeColor = borderColor.cgColor
frameLayer.fillColor = backgroundColor?.cgColor
frameLayer.shadowOffset = shadowOffset
frameLayer.shadowOpacity = shadowOpacity
frameLayer.shadowRadius = shadowRadius
frameLayer.shadowColor = shadowColor.cgColor

layer.mask = frameLayer
layer.insertSublayer(frameLayer, at: 0)