ios - SWIFT 在 Main.storyboard 中定义的 UIImageview 中旋转图像

标签 ios iphone swift uiimageview image-rotation

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

我有一个 IBOutlet 定义为:

@IBOutlet weak var imageToRotate: UIImageView!

我试图以最右侧和高度中间的旋转中心旋转它,根据苹果文档和此处的一些帖子,我使用了 anchor :

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

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

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

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

我尝试使用:

imageToRotate.center = CGPointMake( 487, 160)

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

我想我在这里遗漏了一些东西,但我没弄清楚它是什么。我是否必须定义子层或其他东西? 此外,仅发布 anchor 就会移动图像这一事实告诉我,我遗漏了一些东西。

在类定义中,我使用了它并将它链接到 Storyboard的 UIImage:

@IBOutlet weak var imageToRotate: UIImageView!

在 viewDidLoad() 的重写中我使用了这个:

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

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

谢谢。

最佳答案

要围绕一个点进行评分,您真正需要做的就是结合平移和旋转。平移是 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

这会围绕新的旋转轴创建以下旋转: enter image description here

关于ios - SWIFT 在 Main.storyboard 中定义的 UIImageview 中旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27658454/

相关文章:

ios - Swift 中的 API 网关,什么是 AWSModel 的最佳实践

ios - 如何将 NSExceptionDomains 添加到 xcode 版本 7.0.1 的 plist?

ios - tabbar 没有显示在 secondview Controller 中

ios - 应用程序中的状态栏消失了(Xcode iphone)

ios - ScrollView 不覆盖所有宽度

ios - 如何仅在 swift 代码中更改 TabBar 标题字符串的背景颜色

iphone - iPod运行4.2背景图片有轻微错误,当iPhone模拟器4.2正常

GoogleService-Info.plist 文件中的 iOS Firebase IS_ADS_ENABLED 标志

iOS:使用自定义 UITableViewCell 还是使用 Cell viewWithTag?

iOS:LocationManager 更新,什么时候停止更新?