Reputation: 307
I'm adding a text label on top of a UIImage. I am successfully able to add the text label, however I would like to rotate it 90 degrees so that it's vertical.
This is the code that I have:
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
UITextView *myText = [[UITextView alloc] init];
myText.font = [UIFont fontWithName:@"font-name" size:300.0f];
myText.textColor = [UIColor whiteColor];
myText.text = @"Text";
myText.backgroundColor = [UIColor clearColor];
[myText setTransform:CGAffineTransformMakeRotation(-90* M_PI/180)];
CGSize maximumLabelSize = CGSizeMake(image.size.width,image.size.height);
CGSize expectedLabelSize = [myText.text sizeWithFont:myText.font
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
myText.frame = CGRectMake(image.size.width - expectedLabelSize.width, image.size.height - expectedLabelSize.height, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[myText.text drawInRect:myText.frame withFont:myText.font];
UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I tried transforming the Text View using this:
[myText setTransform:CGAffineTransformMakeRotation(-90* M_PI/180)];
as well as:
[myText setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
But it's not working at all, nothing happens. Would appreciate any help!
Upvotes: 1
Views: 47
Reputation: 15331
You are drawing the text using [myText.text drawInRect:myText.frame withFont:myText.font];
but you are rotating the view that you are getting the text from. If you want to draw a string this way you need to rotate the context then draw. For example:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextRotateCTM(context,-M_PI / 2);
[myText.text drawInRect:myText.frame withFont:myText.font];
CGContextRestoreGState(context);
This will essentially rotate the canvas, draw the string, then rotate the canvas back.
It is likely easier to just rotate a view with a transparent background though.
Upvotes: 2