SWIFT rotating an image in an UIImageview defined in the Main.storyboard

[亡魂溺海] 提交于 2019-12-12 15:01:31

问题


I'm new to SWIFT and I'm practicing to learn but I'm having some difficulty with something. I have an image in an UIImageview defined at the Main.storyboard that I need to rotate.

I have an IBOutlet defined as:

@IBOutlet weak var imageToRotate: UIImageView!

I was trying to rotate it with the center of rotation on the rightmost side and middle of height and as per the apple documentation and some posts in here I used the anchorPoint:

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

Then I try to rotate it using the transform:

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

The image is defined in the Main.storyboard and it looks good when it loads but when I issue the anchorPoint the image gets shifted to the left and the right edge goes to where the center of the image used to be and the rotation happens around that point.

I tried using:

imageToRotate.center = CGPointMake( 487, 160)

to move the image back to the place where it's supposed to be but it doesn't move so that also has me confused.

I think I'm missing something here but I fail to figure out what it is. Do I have to define a sublayer or something else? Also the fact that just issuing the anchorpoint moves the image tells me there's something I'm missing.

In the class definition I used this and got it linked to the storyboard's UIImage:

@IBOutlet weak var imageToRotate: UIImageView!

inside the override of viewDidLoad() I used this:

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

imageToRotate.transform = CGAffineTransformMakeRotation(CGFloat( myRadians ) )

Thanks.


回答1:


All you really need to do to rate around a point is combine a translation and a rotation. The translation is an x and y coordinate with the origin at the center of the image. The rotation is a CGFloat in radians. It may look something like this:

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

This creates the following rotation around the new axis of rotation:



来源:https://stackoverflow.com/questions/27658454/swift-rotating-an-image-in-an-uiimageview-defined-in-the-main-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!