swift - 在 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
}
解决方案
让我们解释一下效果:
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))
推荐阅读
- python - 如何根据生成的随机问题“选择”正确的用户答案
- java - 从类扩展时,何时在方法中使用 super 或 override?
- python - 如何使用 scikit-learn 可视化两个类的边界/决策函数
- javascript - Microsoft Translate Voice 请求时限制 200-400 字
- python - 在 Visual Studio 代码中配置输出屏幕
- python-2.7 - 使用 selenium 和 python 在 Chrome v62 及更高版本中无法处理警报
- vba - VBA:限定动态范围的工作表
- c# - 使用 .net 结合参数和表单数据调用 API 方法
- ajax - AJAX 和 WebSocket 响应混合
- mysql - mysql无法将列从查询传递到嵌套子查询