如何将Corner Radius设置为UIBezierPath

时间:2018-05-26 09:20:39

标签: ios swift uibezierpath

我使用此代码

创建了UIBezierPath的以下图片
    //// Bezier Drawing
    let bezierPath = UIBezierPath()
    bezierPath.move(to: CGPoint(x: 360, y: 0))
    bezierPath.addCurve(to: CGPoint(x: 360, y: 75), controlPoint1: CGPoint(x: 359.53, y: 30.5), controlPoint2: CGPoint(x: 359.91, y: 55.45))
    bezierPath.addCurve(to: CGPoint(x: 360, y: 153.78), controlPoint1: CGPoint(x: 360.35, y: 153.21), controlPoint2: CGPoint(x: 360, y: 153.78))
    bezierPath.addCurve(to: CGPoint(x: 180, y: 153.78), controlPoint1: CGPoint(x: 360, y: 153.78), controlPoint2: CGPoint(x: 271.2, y: 212.77))
    bezierPath.addCurve(to: CGPoint(x: 0, y: 153.78), controlPoint1: CGPoint(x: 88.8, y: 94.8), controlPoint2: CGPoint(x: 0, y: 153.78))
    bezierPath.addLine(to: CGPoint(x: 0, y: 0))
    bezierPath.addLine(to: CGPoint(x: 360, y: 0))
    UIColor.green.setFill()
    bezierPath.fill()

enter image description here

现在我想使用Slider将角半径赋予此跟随图像的TopLeftTopRight

我试过以下代码,但它对我不起作用。

        var cornerPath = path

        cornerPath = UIBezierPath(roundedRect:self.imgTop.bounds,
                                          byRoundingCorners:[.topLeft, .topRight],
                                          cornerRadii: CGSize(width: CGFloat(cornerRadius),
                                                              height: CGFloat(cornerRadius)))

        path.lineWidth = 1.0

        let maskLayer = CAShapeLayer()
        maskLayer.path = cornerPath.cgPath
        self.imgTop.layer.mask = maskLayer
    let maskLayerTop = CAShapeLayer()
    maskLayerTop.fillColor = UIColor.white.cgColor
    maskLayerTop.backgroundColor = UIColor.clear.cgColor
    maskLayerTop.path = pathTop?.cgPath
    maskLayerTop.cornerRadius = CGFloat(cornerRadius)
    //maskLayerTop.masksToBounds = true

    maskLayerTop.shadowRadius = CGFloat(cornerRadius)
    maskLayerTop.fillColor = UIColor.green.cgColor
    maskLayerTop.shadowColor = UIColor.blue.cgColor

    imgTop.layer.mask = maskLayerTop

我还尝试将角半径应用于图像视图,但它不起作用。我希望角半径如下图所示。

enter image description here

请帮忙!

注意:我已创建一条路径来创建以下图片

1 个答案:

答案 0 :(得分:3)

在你的bezierPath = UIBezierPath()for curve add

之前

var = cornerRadiudSize = CGSize(width: 50.0, height: 50.0) //this is your global variable that you can change based on the slider and then draw
let p = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: cornerRadiudSize)
p.addClip()

PS:代替所有角落设置你想要的角落

image worth a thousand words