如何用UIBezierPath绘制曲折线?

时间:2014-10-23 02:59:45

标签: ios objective-c uikit drawing

我有2个已知的CGPoints,我想在2点之间做一个锯齿状的锯齿形样式线。我知道点之间的距离,以及大约需要多少行,这是根据距离动态设置的。

任何指导都将不胜感激。

2 个答案:

答案 0 :(得分:0)

以下是swift中的代码示例,我最近为了获得此效果而编写。此示例将视图作为输入并将Zig-zag效果应用于该视图。您可以参考代码来创建两点效果。

func applyZigZagEffect(givenView: UIView) {
    let width = givenView.frame.size.width
    let height = givenView.frame.size.height

    let givenFrame = givenView.frame
    let zigZagWidth = CGFloat(7)
    let zigZagHeight = CGFloat(5)
    let yInitial = height-zigZagHeight

    var zigZagPath = UIBezierPath()
    zigZagPath.moveToPoint(CGPointMake(0, 0))
    zigZagPath.addLineToPoint(CGPointMake(0, yInitial))

    var slope = -1
    var x = CGFloat(0)
    var i = 0
    while x < width {
        x = zigZagWidth * CGFloat(i)
        let p = zigZagHeight * CGFloat(slope)
        let y = yInitial + p
        let point = CGPointMake(x, y)
        zigZagPath.addLineToPoint(point)
        slope = slope*(-1)
        i++
    }
    zigZagPath.addLineToPoint(CGPointMake(width, 0))

    var shapeLayer = CAShapeLayer()
    shapeLayer.path = zigZagPath.CGPath
    givenView.layer.mask = shapeLayer
}

您可以调整zigZagWidth和zigZagHeight以获得您选择的效果。

答案 1 :(得分:0)

这将在视图顶部创建锯齿形线。您可以在曲折线中传递所需的边数。

public extension UIBezierPath  {
func zigZagTop(_ rect: CGRect) -> UIBezierPath {
    let edges = 10
    let cornerWidth = rect.size.width / CGFloat(edges)
    let cornerHeight = cornerWidth/2
    for i in 0...edges {
        let newHeight = (i % 2) == 0 ? cornerHeight : 0
        if i == 0 {
            move(to: CGPoint(x:rect.size.width, y:newHeight))
        } else {
        addLine(to: CGPoint(x: rect.size.width - cornerWidth * CGFloat(i) , y: newHeight))
        }
    }
    addLine(to: CGPoint(x: 0, y:rect.size.height))
    addLine(to: CGPoint(x: rect.size.width, y:rect.size.height))
    close()
    return self
}
}