【问题标题】:how to rotate CALayer at one point如何在某一点旋转 CALayer
【发布时间】:2010-10-13 18:45:11
【问题描述】:

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

【问题讨论】:

    标签: iphone core-animation


    【解决方案1】:
    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 在包含视图的坐标空间中。

    【讨论】:

    • 你救了我的命!谢谢!!
    【解决方案2】:

    1. 定义要旋转的子图层;
    2. 在超级层和anchorPoint中设置其boundspositionanchorPoint 具有相对坐标并指向anchorPoint。您的子图层将围绕此 anchorPoint 旋转;
    3. 添加转换。

    例如,要围绕子图层的底部中心在其父视图顶部中心点上旋转子图层,请使用以下代码:

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

    【讨论】:

    • 不知道为什么(可能是因为坐标系误导),但建议的代码只有在我将anchorPoint 更改为CGPoint(x: 0.5, y: 0) 时才有效,感谢您的详细回答,非常有用
    • 使用forKeynil 添加动画如果多次使用会增加内存使用率
    【解决方案3】:

    查看 CA 文档here

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

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

    【讨论】:

    • 这仅适用于围绕当前中心旋转图层,而不是任意点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2011-01-24
    • 2011-02-02
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多