【问题标题】:Rotate UIImageView around its center point?围绕其中心点旋转 UIImageView?
【发布时间】:2013-11-12 06:53:59
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 图片文件的中心是黑白圆圈吗?
  • @godel9 是的,黑白圆圈在图片文件的中心

标签: ios iphone objective-c uiimageview cgaffinetransform


【解决方案1】:

你试试这个代码

  - (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

【讨论】:

  • 谢谢!这行得通,我必须进行一些更改,并将动画的 fillMode 设置为 kCAFillModeFowards。理想情况下,我想在动画完成后使用 UIView 的 API 做一些其他的事情,还有其他方法吗?
【解决方案2】:

我发现完成我需要的代码比@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"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2013-09-22
    相关资源
    最近更新 更多