UILabel text truncates when rotated. How to fix?
I am creating a watermark to overlay on top of an image view. The image can be panned, zoomed, etc.
I have created a watermark view class that, when sized, overlays a text label that is as big as will fit in the bounds. This works great and sizes appropriately as the image is sized, etc.
Now I want to rotate the label. As soon as I apply the transform, the text in the label truncates. I assume I am close, but am doing something silly because I am new at this. Any ideas?
Here is my class:
@interface WatermarkView ()
- (CGFloat)biggestBoldFontForString:(NSString*)text inRect:(CGRect)rect;
@end
@implementation WatermarkView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// create a label that will display the watermark
mainLabel = [[UILabel alloc] initWithFrame:frame];
mainLabel.alpha = 0.35;
mainLabel.backgroundColor = [UIColor clearColor];
mainLabel.text = @"watermark";
mainLabel.font = [UIFont boldSystemFontOfSize:[self biggestBoldFontForString:mainLabel.text inRect:mainLabel.frame]];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
// rotate label to a random slanted angle
mainLabel.transform = CGAffineTransformMakeRotation(RANDOM_FLOAT(-M_PI/5, -M_PI/6));
[self addSubview:mainLabel];
}
return self;
}
- (void)dealloc
{
[mainLabel release];
[super dealloc];
}
- (C开发者_如何学运维GFloat)biggestBoldFontForString:(NSString*)text inRect:(CGRect)rect
{
CGFloat actualFontSize = 200;
[text sizeWithFont:[UIFont boldSystemFontOfSize:200] minFontSize:1 actualFontSize:&actualFontSize forWidth:rect.size.width lineBreakMode:0];
return actualFontSize;
}
- (void)layoutSubviews
{
[super layoutSubviews];
mainLabel.font = [UIFont boldSystemFontOfSize:[self biggestBoldFontForString:mainLabel.text inRect:self.frame]];
}
@end
A simple solution might be to simply create a second label, like your first, but adapted to the rotated view. Keep it hidden or alpha=0, then on rotation hid the initial textView and unhide the new Text.
Another issue may be that your frame is too small, once rotated, try keeping the font the size you want and text aligned center, but make the TextView frame much larger than you think you need.
The reason the label truncates after a rotation transform is the bounds shrink. The solution is to store the width of the label before rotation and reassign after didRotateFromInterfaceOrientation.
e.g.
@synthesize labelWidth
(void)viewDidLoad
{
self.labelWidth = _label.bounds.size.width;
_label.transform = CGAffineTransformMakeRotation(-1.3f);
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGRect bounds = _label.bounds;
bounds.size.width = self.labelWidth;
_label.bounds = bounds;
}
精彩评论