如何在带有圆角/圆弧路径的阴影UIView中删除圆弧边界?

时间:2018-09-23 12:36:56

标签: swift uibezierpath rounded-corners

我有这样的门票视图

TicketView

我的方法是我有2个视图,1个是票证本身,另一个是阴影。我之所以必须这样做,是因为如果我遮罩了该视图,它会被裁剪,并且阴影不会出现在票证视图中。

以下是用于创建票证视图的代码:

let shapeLayer = CAShapeLayer()
shapeLayer.frame = someView.bounds
shapeLayer.path = UIBezierPath(roundedRect: someView.bounds,
                               byRoundingCorners: [UIRectCorner.bottomLeft,UIRectCorner.bottomRight] ,
                               cornerRadii: CGSize(width: 5.0, height: 5.0)).cgPath


let rect = CGRect(x:0, y:0, width:200, height:100)
let cornerRadius:CGFloat = 5
let subPathSideSize:CGFloat = 25

let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
let leftSubPath = UIBezierPath(arcCenter: CGPoint(x: rect.width / 2, y: 0),
                               radius: subPathSideSize / 2, startAngle: .pi, endAngle: .pi * 0, clockwise: false)
leftSubPath.close()

let rightSubPath = UIBezierPath(arcCenter: CGPoint(x: rect.width / 2, y: rect.height),
                                radius: subPathSideSize / 2, startAngle: .pi, endAngle: .pi * 0, clockwise: true)
rightSubPath.close()

path.append(leftSubPath)
path.append(rightSubPath.reversing())

let mask = CAShapeLayer()
mask.frame = shapeLayer.bounds
mask.path = path.cgPath
someView.layer.mask = mask

注意:SomeViewTicketView

这是添加阴影的代码:

let shadowMask = CAShapeLayer()
shadowMask.frame = shadowView.bounds
shadowMask.path = path.cgPath
shadowMask.shadowOpacity = 0.2
shadowMask.shadowRadius = 4
shadowMask.masksToBounds = false
shadowMask.shadowOffset = CGSize(width: 0, height: 2)

shadowView.backgroundColor = UIColor.clear
shadowView.layer.addSublayer(shadowMask)

阴影使弧形/圆角具有像这样的边框(用红色圆圈标记)。

view with border on corner

这是我的Playground gist

您知道如何删除圆角和圆弧路径中的边框吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

因此,我认为对蒙版和路径中的角有不同的计算。因此,我使用了shadowLayer的fillColor来匹配CouponView的颜色。而现在,边界已经消失了。

shadowLayer.fillColor = someView.backgroundColor.cgColor

答案 1 :(得分:0)

u需要在您编写的此块中添加clipToBounds。

let mask = CAShapeLayer()
mask.frame = shapeLayer.bounds
mask.path = path.cgPath
someView.clipsToBounds = true
someView.layer.mask = mask