如何在一个选定点旋转CALayer。
答案 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
是您想要旋转的点。 center
和rotationPoint
位于包含视图的坐标空间中。
答案 1 :(得分:4)
bounds
中设置其position
,anchorPoint
。 anchorPoint
具有相对坐标并指向anchorPoint
。您的子图层将围绕此anchorPoint
; 例如,要在子图层底部中心周围的超视图顶部中心点旋转子图层,请使用以下代码:
// 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);