我有一个围绕其中心旋转的UIImageView:
imageHorizon.layer.anchorPoint = CGPointMake(0.5, 0.5);
imageHorizon.transform = CGAffineTransformRotate(imageHorizon.transform, angleToRotate*(CGFloat)(M_PI/180));
有时我也会将此图像向左或向右移动,然后再次旋转。我想一直保持旋转中心在同一点(实际上是超视图的中心)。我怎么能这样做?
欢呼声,
答案 0 :(得分: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];
答案 1 :(得分:3)
这是一个较旧的问题,但其他解决方案对我来说效果不佳,所以我想出了另一个解决方案:
旋转图像基本上只是应用平移的正常旋转,确保旋转后要旋转的点仍然在同一点。要做到这一点,在旋转之前计算图像中的位置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);
答案 2 :(得分:1)
您可以将图像作为另一个视图的子视图,然后旋转超级视图以获得该效果。另一种方法是按照docs。
中的描述设置anchorPoint
属性
答案 3 :(得分: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];
}];