围绕它的中心点旋转UIImageView?

我有一个UIImageView( self.myImage )内的透明PNG,我想围绕其中心点旋转。 代码应该很简单:

 [self.myImage.layer setAnchorPoint:CGPointMake(0.5, 0.5)]; [UIView animateWithDuration:1.0 animations:^{ [self.myImage setTransform:CGAffineTransformMakeRotation(angle)]; }]; 

图像以正确的速度/时间以正确的angular度旋转,但其位置被移位。 这是一个发生了什么的例子:

在这里输入图像说明

灰色方块只是显示在屏幕上的位置。 透明png(包含在UIImageView中)是另一个graphics。 白色虚线显示了UIImageView的中心。 图像的左侧显示图像的原始位置,右侧显示的是用上面的代码旋转后的图像(它向右偏移一点)。 黑白圆圈在图像文件的中心。

有什么我失踪? 据我所知,上面的第一行不是必需的,因为这些是默认值。 我是否必须在故事板/编程设置中设置/取消设置?

你只是尝试这个代码

  - (void)viewDidLoad { [super viewDidLoad]; CATransform3D transform = CATransform3DIdentity; transform.m34 = -1 / 500.0; transform = CATransform3DRotate(transform, .0 * M_PI_2, 1, 0, 0);/*Here the angle of transform set (Here angle set as 0)*/ self.transformView.layer.transform = transform; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.fromValue = [NSNumber numberWithFloat:0]; animation.toValue = [NSNumber numberWithFloat:2 * M_PI]; animation.duration = 3.0; animation.repeatCount = HUGE_VALF; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [self.discView.layer addAnimation:animation forKey:@"transform.rotation.z"]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.discView.layer removeAllAnimations]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } 

在这个你只需要改变transformView与另一个视图或ImageView

我发现我所需要的代码比@Albin Joseph给出的要简单得多,但它确实指向了正确的方向。 我的animation需要从停止的位置转到新的位置。 有些时候会animation,有时候不会。 所以代码如下:

 CGFloat duration = animated ? 0.5 : 0.01; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.fromValue = [[self.turnIndicatorImage.layer presentationLayer] valueForKeyPath:@"transform.rotation.z"]; animation.toValue = angle; animation.duration = duration; animation.fillMode = kCAFillModeForwards; animation.repeatCount = 0; animation.removedOnCompletion = NO; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [self.turnIndicatorImage.layer addAnimation:animation forKey:@"transform.rotation.z"];