Search code examples
iosobjective-cswiftcore-graphicsdraw

iOS: Draw "Movable Polygon" with Core Graphics


I would like to draw a UIBerzierPath (e.g. a Rectangle with 4 CGPoints) in Core Graphics and and change its position, maybe also its size (e.g. bigger width, smaller height), which means, the four Points of the UIBerzierPath change.

How can I get this change in appearance as animation (so that the points and edges move to its new position), instead of just drawing the new one?


Solution

  • Create a CAShapeLayer

    let pathLayer = CAShapeLayer()
    let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100))
    pathLayer.path = path.cgPath
    pathLayer.strokeColor = UIColor.red.cgColor
    
    pathLayer.strokeColor = UIColor.red.cgColor
    pathLayer.fillColor = UIColor.green.cgColor
    pathLayer.fillRule = kCAFillRuleEvenOdd
    
    self.view.layer.addSublayer(pathLayer)
    

    Animate it like so:

    let animation = CABasicAnimation(keyPath: "path")
    animation.toValue = UIBezierPath(rect: CGRect(x: 200, y: 200, width: 100, height: 100)).cgPath
    animation.duration = 1
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeBoth
    animation.isRemovedOnCompletion = false
    pathLayer.add(animation, forKey: animation.keyPath)