围绕其中心点旋转UIImageView? [英] Rotate UIImageView around its center point?

查看:275
本文介绍了围绕其中心点旋转UIImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a transparent png inside a UIImageView (self.myImage) that I want to rotate around its center point. The code should be pretty simple:

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

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

The image rotates at the right speed/time and at the right angle, but its position gets shifted. Here's an example of what's happening:

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

The gray square is just to show position in the screen. The transparent png (contained in a UIImageView) is the other figure. The white dotted lines show the center of the UIImageView. The left side of the image shows the original position of the image, the right side shows the image after being rotated with the above code (which gets shifted a little down to the right). The black and white circles are in the center of the image file.

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

Is there something that I'm missing? As far as I understand, the first line above is not required because those are the defaults. Do I have to set/unset something in the storyboard/programmatically?

推荐答案

我发现我需要完成的代码是什么我需要的比@Albin Joseph给出的更简单,但确实指向了正确的方向。
我的动画需要从它停止的位置开始拾取并旋转到新位置。有时它会动画,有时则不会。因此代码:

I found out that the code I need to accomplish what I needed was simpler than the one given by @Albin Joseph, but it did point me to the right direction. My animation needs to pick up where it left off and rotate to a new position. Some times it will be animated and sometimes it won't. So hence the code:

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

这篇关于围绕其中心点旋转UIImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆