将拐角半径设置为负值以实现凹角

时间:2017-11-26 13:58:27

标签: swift calayer

我使用此代码围绕UIView

的角落
extension UIView {

    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        self.layer.masksToBounds = false
    }
}

然后我使用了view.roundCorners([.topLeft, .topRight], radius: view.frame.width/3)

现在这会使角落成凸,我希望相反。意味着顶角将保持在相同的点,但它们之间的线是朝着视图的内部圆化。 我尝试通过使用负值调用上述函数来实现此目的,但这导致没有发生任何事情。

我添加了一张图片,让我的目标更加清晰。 我怎么能实现这个目标? enter image description here

1 个答案:

答案 0 :(得分:2)

您需要创建自己的UIBezierPath。对于凹端,addQuadCurve(to:controlPoint:)派上用场。

我在这里使用参数depth来控制曲线的数量:

extension UIView {

    func concaveEnds(depth: CGFloat) {
        let width = self.bounds.width
        let height = self.bounds.height

        let path = UIBezierPath()
        path.move(to: CGPoint.zero)
        path.addLine(to: CGPoint(x: width, y: 0))
        path.addQuadCurve(to: CGPoint(x: width, y: height), controlPoint: CGPoint(x: width - height * depth, y: height / 2))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.addQuadCurve(to: CGPoint.zero, controlPoint: CGPoint(x: height * depth, y: height / 2))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        self.layer.masksToBounds = false
    }
}

游乐场中的演示:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .red

view.concaveEnds(depth: 0.4)

Demo in Playground Demo with less curve