簡體   English   中英

圍繞任意點旋轉UIImageView

[英]rotate UIImageView around an arbitrary point

我有一個UIImageView,它圍繞其中心旋轉:

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

有時我還會將此圖像向左或向右移動,然后再次旋轉。 我想一直將旋轉中心保持在同一點(實際上是超級視圖的中心)。 我怎樣才能做到這一點 ?

干杯,

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];

這是一個比較老的問題,但是其他解決方案對我來說效果不佳,因此我想出了另一個解決方案:

旋轉圖像本質上只是應用了平移的普通旋轉,請確保要旋轉的點在旋轉后仍位於同一點。 為此,請在旋轉之前計算圖像中位置的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);

您可以使圖像成為另一個視圖的子視圖,然后旋轉超級視圖以獲得該效果。 另一種方法是按照docs中的說明設置anchorPoint屬性。

我正在使用此代碼圍繞點(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];
                     }];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM