7

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

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

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

在此处输入图像描述

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

有什么我想念的吗?据我了解,上面的第一行不是必需的,因为这些是默认值。我是否必须以编程方式在情节提要中设置/取消设置某些内容?

4

2 回答 2

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

在此您只需将 transformView 更改为另一个视图或 ImageView

于 2013-11-12T07:07:33.520 回答
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"];
于 2014-05-20T15:38:35.350 回答