围绕其中心点旋转UIImageView?

时间:2013-11-12 06:54:00

标签: ios iphone objective-c uiimageview cgaffinetransform

我在UIImageView(self.myImage)中有一个透明的png,我想围绕它的中心点旋转。 代码应该非常简单:

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

图像以正确的速度/时间和直角旋转,但其位置会发生偏移。以下是正在发生的事情的一个例子:

enter image description here

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

有什么东西我不见了吗?据我所知,上面的第一行不是必需的,因为这些是默认值。我是否必须在故事板中以编程方式设置/取消设置某些内容?

2 个答案:

答案 0 :(得分:13)

您只需尝试此代码

  - (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);
  }

在此,您只需使用其他视图或ImageView

更改transformView

答案 1 :(得分:5)

我发现我需要完成我需要的代码比@Albin Joseph给出的代码简单,但它确实指向了正确的方向。 我的动画需要从中断的位置继续拾取并旋转到新位置。有时它会动画,有时它不会。因此代码:

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