2011-07-29 101 views
1

我有圍繞其中心旋轉一個UIImageView:旋轉的UIImageView周圍任意點

imageHorizon.layer.anchorPoint = CGPointMake(0.5, 0.5); 
imageHorizon.transform = CGAffineTransformRotate(imageHorizon.transform, angleToRotate*(CGFloat)(M_PI/180)); 

有時我也在這個圖像移動到左或右,然後再旋轉。我希望始終將旋轉中心保持在同一點(實際上是超級視圖的中心)。我怎樣才能做到這一點 ?

歡呼聲,

回答

1

您可以使圖像的另一視圖的子視圖,然後旋轉上海華來獲得這種效果。另一種方法是設置anchorPoint屬性,如docs中所述。

+0

謝謝我正要發佈子視圖解決方案,我發現了:) – Jan

5
self.imgView.layer.anchorPoint = CGPointMake(0.0,1.0); 
self.imgView.layer.position = CGPointMake(100,200.0); 
CGAffineTransform cgaRotateHr = CGAffineTransformMakeRotation(-(3.141/4)); 
[self.imgView setTransform:cgaRotateHr]; 
2

這是一個老問題,但其他的解決方案並沒有爲我工作得很好,所以我想出了另一種解決方案:

旋轉圖像本質上是應用只是一個翻譯正常旋轉,確保你想旋轉的點在旋轉後仍然在同一個點上。爲此,請在旋轉前計算圖像中位置的CGPoint,在旋轉後獲取位置,並將差異作爲圖像上的平移,將其「捕捉」到正確的位置。下面是我一直在使用的代碼:

請記住,翻譯應通過CGAffineTransform應用,不要移動.center,因爲翻譯需要相對於旋轉,而CGAffineTransformTranslate()需要關心這一點。

// Note: self is the superview of _imageView 

// Get the rotation point 
CGPoint rotationPointInSelf = self.center; // or whatever point you want to rotate around 
CGPoint rotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self]; 

// Rotate the image 
_imageView.transform = CGAffineTransformRotate(_imageView.transform, angle); 

// Get the new location of the rotation point 
CGPoint newRotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self]; 

// Calculate the difference between the point's old position and its new one 
CGPoint translation = CGPointMake(rotationPointInImage.x - newRotationPointInImage.x, rotationPointInImage.y - newRotationPointInImage.y); 

// Move the image so the point is back in it's old location 
_imageView.transform = CGAffineTransformTranslate(_imageView.transform, -translation.x, -translation.y); 
+0

很好的答案!謝謝! –

0

我正在使用此代碼繞點(0,0)旋轉。 也許它可以幫助你弄清楚如何激活你想要的。

float width = self.view.frame.size.width; 
    float height = self.view.frame.size.height; 

    CGRect frame_smallView = CGRectMake(-width, -height, width, height); 
    UIView *smallView = [[UIView alloc] initWithFrame:frame_smallView]; 
    smallView.backgroundColor = darkGrayColor; 

    // Select x and y between 0.0-1.0. 
    // The default is (0.5f,0.5f) that is the center of the layer 
    // (1.0f,1.0f) is the right bottom corner 
    smallView.layer.anchorPoint = CGPointMake(1.0f, 1.0f); 

    // Rotate around this point 
    smallView.layer.position = CGPointMake(0, 0); 

    [self.view insertSubview:smallView belowSubview:self.navBar]; 

    [UIView animateWithDuration:1 
        animations:^{ 
         smallView.transform = CGAffineTransformMakeRotation(M_PI); 
        } 
        completion:^(BOOL finished){ 
         [self.navigationController popViewControllerAnimated:NO]; 
        }];