How can I have the text scale to fit the bounds I gave it?
I've done something like this in the past.
-(void)calcFontSizeToFitRect:(NSRect)r {
float targetWidth = r.size.width - xMargin;
float targetHeight = r.size.height - yMargin;
// the strategy is to start with a small font size and go larger until I'm larger than one of the target sizes
int i;
for (i=minFontSize; i<maxFontSize; i++) {
NSDictionary* attrs = [[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:currentFontName size:i], NSFontAttributeName, nil];
NSSize strSize = [stringValue sizeWithAttributes:attrs];
[attrs release];
if (strSize.width > targetWidth || strSize.height > targetHeight) break;
}
[self setCurrentFontSize:(i-1)];
}
The stringValue
variable is the text you want sized. The xMargin
and yMargin
variables are for spacing that you want. The minFontSize
and maxFontSize
variables give limits to how small or large you want to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With