2/28/15

iOS Draw Along Bezier Quad Curve Path


//swift

var bp = UIBezierPath()
let startPoint = CGPointMake(200, 400)
let endPoint = CGPointMake(500, 400)
let controlPoint = CGPointMake(350, 150)
bp.moveToPoint(startPoint)
bp.addQuadCurveToPoint(endPoint, controlPoint:controlPoint)

var vp = CAShapeLayer()  //debug visual path
vp.path = bp.CGPath
vp.fillColor = UIColor.clearColor().CGColor
vp.strokeColor = UIColor.darkGrayColor().CGColor
vp.lineWidth = 1.0
self.view.layer.addSublayer(vp)

    //http://en.wikipedia.org/wiki/Bezier_curve#Quadratic_B.C3.A9zier_curves
    func getBezierQuadXY(t:CGFloat, p0:CGFloat, p1:CGFloat, p2:CGFloat) -> CGFloat 
    {
        return ((1-t) * (1-t)) * p0 + 2 * (1-t) * t * p1 + t * t * p2
    }

    func addNode(pathPercent:CGFloat)
    {
        var node = CALayer()
        node.frame = CGRectMake(0, 0, 20, 20)
        node.cornerRadius = 10.0
        node.borderColor = UIColor.darkGrayColor().CGColor
        node.borderWidth = 1.0
        let p = CGPointMake(getBezierQuadXY(pathPercent, startPoint.x, controlPoint.x, endPoint.x),
                            getBezierQuadXY(pathPercent, startPoint.y, controlPoint.y, endPoint.y))
        node.position = p
        self.view.layer.addSublayer(node)
    }

addNode(0.5)
addNode(0.7)
addNode(0.8)
addNode(0.89)
addNode(1.0)

No comments:

Post a Comment