How 开发者_如何转开发can you rotate text for UIButton
and UILabel
? 90 degrees, 180 degrees.
[*yourlabelname* setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
rotated image
pervious image
Try this:
lbl.transform= CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(270));
I wanted to provide an alternative response.
Instead of rotating the UILabel
, you can rotate the text within the label by deriving a subclass from UILabel
and overriding drawRect
. If you're using Interface Builder, you can specify this subclass instead of UILabel
in the Custom Class attribute of the Identity Inspector. This will allow you to build out your UI with XIBs, instead of programmatically creating the labels. The only caveat being that the text in Interface Builder will display horizontally. However, it will be rendered vertically in the app itself.
#import "RotatedLabel.h"
@implementation RotatedLabel
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextRotateCTM(context, -(M_PI/2));
UIFont* systemFont17 = [UIFont systemFontOfSize:17.0];
CGSize textSize = [self.text sizeWithFont:systemFont17];
CGFloat middle = (self.bounds.size.width - textSize.height) / 2;
[self.text drawAtPoint:CGPointMake(-self.bounds.size.height, middle) withFont:systemFont17];
CGContextRestoreGState(context);
}
@end
You do like this,
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 70)];
label.numberOfLines = 2;
label.text = @"text";
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.highlightedTextColor = [UIColor blackColor];
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont systemFontOfSize:12];
//rotate label in 45 degrees
label.transform = CGAffineTransformMakeRotation( M_PI/4 );
[self addSubview:label];
[label release];
In my experience, the UIView frame is changed after applying the transform, so this is what I've used:
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(x, 0, 28, 159)];
l.textAlignment = NSTextAlignmentRight;
l.text = @"Hello!";
[_viewXAxisLabels addSubview:l];
[l setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
l.frame = CGRectMake(x, 0, 28, 159);
lbl.transform=CGAffineTransformMakeRotation(M_PI);
//Go back
lbl.transform=CGAffineTransformMakeRotation(0);
//Right To Left
lable.transform = CGAffineTransformMakeRotation (3.14/2);
//Left To Right
[lable setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
OR
lable.transform= CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(270));
精彩评论