2010-10-13 36 views

回答

34
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位於包含視圖的座標空間中。

+0

感謝warrenm其工作....... – 2010-10-14 11:37:37

+0

你救了我的日子!謝謝!! – 2013-04-26 21:29:28

1

查看CA文檔here

你想設置的轉換爲CATransform3DRotate,例如:

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

這將只足夠用於層關於其當前中心,而不是任意的旋轉點。 – warrenm 2010-10-14 02:47:59

2

enter image description here

  1. 定義要旋轉你的子層;
  2. 設置它的bounds,position在超級層和anchorPointanchorPoint有相對座標並且指向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)