如何在一个点旋转CALayer

时间:2010-10-13 18:45:12

标签: iphone core-animation

如何在一个选定点旋转CALayer。

3 个答案:

答案 0 :(得分:37)

CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DTranslate(transform, rotationPoint.x-center.x, rotationPoint.y-center.y, 0.0);
transform = CATransform3DRotate(transform, rotationAngle, 0.0, 0.0, -1.0);
transform = CATransform3DTranslate(transform, center.x-rotationPoint.x, center.y-rotationPoint.y, 0.0);

center是图层的中心,rotationAngle以弧度为单位(正向为逆时针方向),rotationPoint是您想要旋转的点。 centerrotationPoint位于包含视图的坐标空间中。

答案 1 :(得分:4)

enter image description here

  1. 定义要旋转的子图层;
  2. 在超级层和bounds中设置其positionanchorPointanchorPoint具有相对坐标并指向anchorPoint。您的子图层将围绕此anchorPoint;
  3. 旋转
  4. 添加转化。
  5. 例如,要在子图层底部中心周围的超视图顶部中心点旋转子图层,请使用以下代码:

        // 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)
    

答案 2 :(得分:0)

查看CA文档here

您希望将变换设置为CATransform3DRotate,例如:

CATransform3D current = myLayer.transform;
myLayer.transform = CATransform3DRotate(current, DEGREES_TO_RADIANS(20), 0, 1.0, 0);