【问题标题】:rotate UIImageView around an arbitrary point围绕任意点旋转 UIImageView
【发布时间】:2011-07-29 06:15:14
【问题描述】:
我有一个围绕其中心旋转的 UIImageView:
imageHorizon.layer.anchorPoint = CGPointMake(0.5, 0.5);
imageHorizon.transform = CGAffineTransformRotate(imageHorizon.transform, angleToRotate*(CGFloat)(M_PI/180));
有时我也会将此图像向左或向右移动,然后再次旋转。我想始终将旋转中心保持在同一点(实际上是超级视图的中心)。我该怎么做?
干杯,
【问题讨论】:
标签:
ios
uiimageview
anchor
【解决方案1】:
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);
【解决方案3】:
您可以使图像成为另一个视图的子视图,然后旋转超级视图以获得该效果。另一种方法是设置anchorPoint 属性,如docs 中所述。
【解决方案4】:
我正在使用此代码围绕点 (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];
}];