DigitalDeath
DigitalDeath

Reputation: 155

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

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.

Upvotes: 3

Views: 5495

Answers (1)

Ian
Ian

Reputation: 12768

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: enter image description here

Upvotes: 4

Related Questions