2014-02-07 40 views
0

我正在重新將自己介紹給iOS編程,並且遇到了一個看似簡單的問題。我一直在關注this example about how to rotate a image according to the user's heading。關鍵部分是:如何在它自己的中心周圍旋轉UIImageView?

float heading = -1.0f * M_PI * newHeading.magneticHeading/180.0f; 
arrowImage.transform = CGAffineTransformMakeRotation(heading); 

圖像確實是旋轉的,但中心似乎不是旋轉的錨點。我一直在谷歌搜索,但無法弄清楚。有人能指出我正確的方向嗎?

下面是情況下的截圖並不清楚:在初始狀態,標籤爲中心的圓形和白色方塊在圖像中居中:

+0

您可以直接設置圖層的錨點view.layer.anchorPoint = anchorPoint; – Jack

+0

anchorPoint **默認爲**(0.5,0.5),也就是視圖的中心。還有其他問題在這裏,我們需要更多的細節。 –

+0

你需要什麼樣的細節? – Florian

回答

1

此代碼適用於我:

UIImage *img = [UIImage imageNamed:@"Image.png"]; 
UIImageView *imageToMove = [[UIImageView alloc] initWithImage:img]; 

CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0); 

CABasicAnimation* rotationAnimation; 
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"]; 
rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform]; 
rotationAnimation.duration = 0.6f; 
rotationAnimation.cumulative = YES; 
rotationAnimation.repeatCount = FLT_MAX; 

[imageToMove.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; 
[self.view addSubview:imageToMove]; 
+0

你的x和y不需要以圖像爲中心嗎?這應該仍然(如果文檔是正確的)圍繞圖像的左上角旋轉,而不是圖像的中心。 – trumpetlicks

+0

雖然如此,但它的工作正常,它圍繞圖像的中心旋轉。 – Greg

+0

有趣的知道:-) – trumpetlicks

-1

嘗試此代碼爲您的情況

var angle=0; 

self.btnImage.center=CGPointMake(self.btnImage.center.x, self.btnImage.center.y); 
      self.btnImage.transform=CGAffineTransformMakeRotation (angle); 
      angle+=0.15; 

將上述方法保留在方法中,當您想要更改圖像的角度時使用時間間隔或調用方法。

+1

這個答案太糟糕了,它傷害了。 –