【问题标题】:SWIFT rotating an image in an UIImageview defined in the Main.storyboardSWIFT 在 Main.storyboard 中定义的 UIImageview 中旋转图像
【发布时间】:2014-12-26 14:39:52
【问题描述】:

我是 SWIFT 的新手,我正在练习学习,但我在某些方面遇到了一些困难。 我在 Main.storyboard 中定义的 UIImageview 中有一个图像,需要旋转。

我有一个 IBOutlet 定义为:

@IBOutlet weak var imageToRotate: UIImageView!

我试图用最右边和中间高度的旋转中心旋转它,根据苹果文档和这里的一些帖子,我使用了锚点:

imageToRotate.layer.anchorPoint = CGPointMake( 1.0, 0.5 )

然后我尝试使用变换来旋转它:

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

图像是在 Main.storyboard 中定义的,加载时看起来不错,但是当我发出 anchorPoint 时,图像会向左移动,右边缘会移动到图像的中心位置和旋转位置发生在那个点附近。

我尝试使用:

imageToRotate.center = CGPointMake( 487, 160)

将图像移回它应该在的位置,但它没有移动,这也让我感到困惑。

我想我在这里遗漏了一些东西,但我无法弄清楚它是什么。我是否必须定义一个子层或其他东西? 此外,仅发出锚点会移动图像这一事实告诉我,我缺少一些东西。

在类定义中,我使用了它并将其链接到情节提要的 UIImage:

@IBOutlet weak var imageToRotate: UIImageView!

在 viewDidLoad() 的覆盖中我使用了这个:

imageToRotate.layer.anchorPoint = CGPointMake(1.0, 0.5)

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

谢谢。

【问题讨论】:

    标签: ios iphone swift uiimageview image-rotation


    【解决方案1】:

    要围绕一个点进行评分,您真正需要做的就是将平移和旋转结合起来。平移是一个 x 和 y 坐标,原点位于图像的中心。旋转是以弧度为单位的 CGFloat。它可能看起来像这样:

    let square2 = UIView(frame: CGRectMake(200, 200, 50, 50))
    view.addSubview(square2)
    // Desired point from the center to rotate around
    let x = CGFloat(25)
    let y = CGFloat(0)
    var transform = CGAffineTransformMakeTranslation(x, y)
    transform = CGAffineTransformRotate(transform, CGFloat(M_PI_4))
    transform = CGAffineTransformTranslate(transform,-x,-y)
    square2.backgroundColor = UIColor.magentaColor()
    square2.transform = transform
    

    这会围绕新的旋转轴创建以下旋转:

    【讨论】:

    • 感谢您帮助我。我使用了您的代码,并且得到了与使用其他代码相同的结果。子视图以相同的方式旋转,但也向右移动。我确信这个问题与视图定义有关。我使用以下方法打印了边界: self.waitLabel.text = NSString(format: "%.1f, %.1f, %.1f, %.1f", self.imageToRotate.bounds.origin.x, self.imageToRotate.bounds .origin.y, self.imageToRotate.bounds.maxX, self.imageToRotate.bounds.maxY ) 我得到了全零:0.0, 0.0, 0.0, 0.0
    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 2014-12-25
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多