首页 > 解决方案 > 在 UIView 上创建曲线

问题描述

我需要在 UIView 的顶部和底部创建一条曲线,我在底部使用了以下内容:

 func pathCurvedForView(givenView: UIView, curvedPercent:CGFloat) ->UIBezierPath
        {
            let arrowPath = UIBezierPath()
            arrowPath.move(to: CGPoint(x:0, y:0))
            arrowPath.addLine(to: CGPoint(x:givenView.bounds.size.width, y:0))
            arrowPath.addLine(to: CGPoint(x:givenView.bounds.size.width, y:givenView.bounds.size.height))
            arrowPath.addQuadCurve(to: CGPoint(x:0, y:givenView.bounds.size.height), controlPoint: CGPoint(x:givenView.bounds.size.width/2, y:givenView.bounds.size.height-givenView.bounds.size.height*curvedPercent))
            arrowPath.addLine(to: CGPoint(x:0, y:0))
            arrowPath.close()
            
            return arrowPath
        }

    func applyCurvedPath(givenView: UIView,curvedPercent:CGFloat) {
        guard curvedPercent <= 1 && curvedPercent >= 0 else{
            return
        }
        
        let shapeLayer = CAShapeLayer(layer: givenView.layer)
        shapeLayer.path = self.pathCurvedForView(givenView: givenView,curvedPercent: curvedPercent).cgPath
        shapeLayer.frame = givenView.bounds
        shapeLayer.masksToBounds = true
        givenView.layer.mask = shapeLayer
    }

它工作得很好,但只为视图的底部做了工作,知道如何为 topView 实现它吗?谢谢 在此处输入图像描述

标签: swiftuiviewuibezierpath

解决方案


让我们解释一下效果:

A             B
 + -------- +
 |          |
 |          |
 + -------- +
D            C

我们想要:

  • 从 A (0,0) 开始:move(to:)
  • 弯曲到 B(宽度,0):addQuadCurve(to:controlPoint:)
  • 直接到 C(宽度,高度):addLine(to:)
  • 曲线到 D(0,高度): addQuadCurve(to:controlPoint:)
  • 直接到 A (0,0):addLine(to:)
  • 关。

所以更换

arrowPath.addLine(to: CGPoint(x:givenView.bounds.size.width, y:0))

arrowPath.addQuadCurve(to: CGPoint(x: givenView.bounds.size.width, y: 0), 
                       controlPoint: CGPoint(x: givenView.bounds.size.width/2, 
                                             y: givenView.bounds.size.height*curvedPercent))

推荐阅读