How to rotate UILabel with respect to Top Left corner in iOS

2.9k views Asked by At

I used the following code to rotate the label text

 mylabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))

this will work. But it will rotate UILabel in Center .

let say my Top left corner of UILabel is (10,10) when i rotate it its Top left corner should not be change(Just like radius or circle).

How i can rotate it with respect to Top Left corner ?.

please help me

Edit:

here is code

  var  transA = CGAffineTransformMakeTranslation(mylabel.frame.size.width/2,mylabel.frame.size.height/2);
  var  rotation = CGAffineTransformMakeRotation(CGFloat(M_PI_4));
  var  transB = CGAffineTransformMakeTranslation(-mylabel.frame.size.width/2,-mylabel.frame.size.height/2);


mylabel.transform = CGAffineTransformConcat(CGAffineTransformConcat(transA,rotation),transB);


   var  transform = transA
   mylabel.transform = CGAffineTransformConcat(mylabel.transform, transform)

EDIT Question : how to make my Label look like a radius of Circle. i.e. i can rotate it 360 with respect to origin?

1

There are 1 answers

4
Nils Ziehn On BEST ANSWER

There are two things you can do about this.

A)

You can change the anchor point of the Label:

mylabel.layer.anchorPoint = CGPointMake(0,0); // This will set the anchor point to the top left

Now you can rotate around this point. This will change the anchor point for ALL transforms!

B)

You could do something like this:

CGAffineTransform transA = CGAffineTransformMakeTranslation(mylabel.frame.size.width/2,mylabel.frame.size.height/2);
CGAFfineTransfrom rotation = CGAffineTransformMakeRotation(M_PI_2);
CGAffineTransform transB = CGAffineTransformMakeTranslation(-mylabel.frame.size.width/2,-mylabel.frame.size.height/2);
mylabel.transform = CGAffineTransformConcat(CGAffineTransformConcat(transA,rotation),transB);

This won't change your anchor point and therefore not impact other transforms!

(If the rotation is wrong, you may have to change transA against transB)

UPDATE

If you want to 'keep' rotation (as asked in the comments), you can just do this:

CGAffineTransform transform = ... // Put the transform here that you used in A) or B)

mylayer.transfrom = CGAffineTransfromConcat(mylayer.transform,transform);

This way you just say 'whereever' I was before - rotate 90 (or 45) degrees more

UPDATE 2

Your code should look like this:

var  transA = CGAffineTransformMakeTranslation(mylabel.frame.size.width/2,mylabel.frame.size.height/2);
var  rotation = CGAffineTransformMakeRotation(CGFloat(M_PI_2));
var  transB = CGAffineTransformMakeTranslation(-mylabel.frame.size.width/2,-mylabel.frame.size.height/2);


var transform = CGAffineTransformConcat(CGAffineTransformConcat(transA,rotation),transB);

mylabel.transform = CGAffineTransformConcat(mylabel.transform, transform)