how to rotate CALayer at one point

Viewed 16889

how to rotate CALayer at one selected point.

3 Answers

enter image description here

  1. Define your sublayer that you want to rotate;
  2. Set its bounds, position in superlayer and anchorPoint. anchorPoint has relative coordinates and points to an anchorPoint. Your sublayer will rotate around this anchorPoint;
  3. Add transformation.

For example, to rotate a sublayer on its superview top center point around sublayer's bottom center, use this code:

    // 1
    let rect = CGRect(x: 0,
                      y: 0,
                      width: 20,
                      height: 20)
    let path = UIBezierPath(rect: rect)
    let sublayer = CAShapeLayer()
    sublayer.fillColor = UIColor.green.cgColor
    sublayer.path = path.cgPath
    superlayer.addSublayer(sublayer)

    // 2
    sublayer.bounds = rect
    sublayer.position = CGPoint(x: superlayer.bounds.size.width/2, y: 0)
    sublayer.anchorPoint = CGPoint(x: 0.5, y: 1)

    // 3
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.toValue = 2*CGFloat.pi
    rotationAnimation.duration = 3
    rotationAnimation.fillMode = kCAFillModeForwards
    rotationAnimation.isRemovedOnCompletion = false
    sublayer.add(rotationAnimation, forKey: nil)
Related