【问题标题】:How to rotate an UIImageView around it's own center?如何围绕它自己的中心旋转 UIImageView?
【发布时间】:2014-03-05 00:13:02
【问题描述】:

我正在重新向自己介绍 iOS 编程,但遇到了一个看似简单的问题。我一直在关注this example about how to rotate a image according to the user's heading。关键部分是:

float heading = -1.0f * M_PI * newHeading.magneticHeading / 180.0f;
arrowImage.transform = CGAffineTransformMakeRotation(heading);

图像确实旋转了,但中心似乎不是旋转的锚点。我一直在谷歌搜索,但无法弄清楚。有人能指出我正确的方向吗?

看不清楚的截图如下:初始状态下,标签以圆形为中心,白色方块以图像为中心:

【问题讨论】:

  • 可以直接设置图层的锚点 view.layer.anchorPoint = anchorPoint;
  • anchorPoint is (0.5, 0.5) 默认情况下,也就是视图的中心。这里还有其他问题,我们需要更多细节。
  • 你需要什么样的细节?

标签: ios objective-c uiimageview rotation


【解决方案1】:

此代码适用于我的:

UIImage *img = [UIImage imageNamed:@"Image.png"];
UIImageView *imageToMove = [[UIImageView alloc] initWithImage:img];

CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);

CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 0.6f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = FLT_MAX;

[imageToMove.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
[self.view addSubview:imageToMove];

【讨论】:

  • 你的 x 和 y 不需要以图像为中心吗?这应该仍然(如果文档正确)围绕图像的左上角旋转,而不是图像的中心。
  • 我虽然是这样,但它工作得很好,它围绕图像的中心旋转。
  • 有兴趣知道:-)
  • 这绝对让我更进一步:图像现在围绕其中心旋转。为此非常感谢!每当更新标题并且我希望我的箭头指向固定点/位置时,都会触发旋转动画。我不太明白如何调整代码中的参数以保持“箭头”稳定并指向固定位置。 (抱歉这些低级问题,我才刚刚开始思考这一切......)
【解决方案2】:

根据您的情况尝试此代码

var angle=0;

self.btnImage.center=CGPointMake(self.btnImage.center.x, self.btnImage.center.y);
            self.btnImage.transform=CGAffineTransformMakeRotation (angle);
            angle+=0.15;

将上述方法保留在方法中,使用时间间隔或在您想要更改图像角度时调用该方法。

【讨论】:

  • 这个答案太糟糕了。
【解决方案3】:

Greg 代码的 Swift 端口

    let rotationTransform: CATransform3D = CATransform3DMakeRotation(.pi, 0, 0, 1.0);
    let rotationAnimation = CABasicAnimation(keyPath: "transform");
    rotationAnimation.toValue = NSValue(caTransform3D: rotationTransform)
    rotationAnimation.duration = 0.6;
    rotationAnimation.isCumulative = true;
    rotationAnimation.repeatCount = Float.infinity;
    progressArc.layer.add(rotationAnimation, forKey:"rotationAnimation")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2019-10-22
    • 2013-02-14
    • 1970-01-01
    • 2023-03-07
    • 2017-05-04
    相关资源
    最近更新 更多