【问题标题】:create a curve on top of a UIView在 UIView 上创建曲线
【发布时间】:2020-10-15 12:42:11
【问题描述】:

我需要在 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 实现它吗? 谢谢

【问题讨论】:

  • 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))替换arrowPath.addLine(to: CGPoint(x:givenView.bounds.size.width, y:0))

标签: swift uiview uibezierpath


【解决方案1】:

我们来解释一下效果:

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))

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多