Why do all these methods of measuring string metrics with font attribute fail?
Why do all these methods of measuring string metrics with font attribute fail?
- Subject: Why do all these methods of measuring string metrics with font attribute fail?
- From: an0 <email@hidden>
- Date: Wed, 3 Sep 2008 21:01:59 +0800
I should declare up front that I know there are some arcane ways to
measure string metrics using things like NSTextStorage,
NSLayoutManager and the kin.
Given the string and the font used to render it, it is reasonable
there should be some straightforward way to tell the metrics of the
string when laid out in one line. Actually, I thought I'd found
several after reading through the docs; however, all of them turned
out to be very miserable.
Here goes what I've tried, with the effects in comments:
NSFont *font = [NSFont labelFontOfSize:12]; // I put the string in a label
NSRect fontRect = [font boundingRectForFont]; // too large
NSRect glyphRect = [font boundingRectForGlyph:'W']; // too too small
NSLog(@"fontRect: %f, %f, %f, %f\nglyphRect: %f, %f, %f, %f",
fontRect.origin.x, fontRect.origin.y, fontRect.size.width,
fontRect.size.height, glyphRect.origin.x, glyphRect.origin.y,
glyphRect.size.width, glyphRect.size.height);
NSTextField *label1 = [[[NSTextField alloc] init] autorelease];
[label1 setStringValue:@"ABC"];
[label1 setFrame:NSMakeRect(0, 0, fontRect.size.width * 3,
fontRect.size.height)];
[[box contentView] addSubview:label1]; // box is an NSBox
NSTextField *label2 = [[[NSTextField alloc] init] autorelease];
[label2 setStringValue:@"ABC"];
NSSize size = [@"ABC" sizeWithAttributes:[NSDictionary
dictionaryWithObject:font forKey:NSFontAttributeName]]; // too small
NSLog(@"string size: %f, %f", size.width, size.height);
[label2 setFrame:NSMakeRect(fontRect.size.width * 3, 0,
size.width, size.height)];
[[box contentView] addSubview:label2];
So, can anyone tell me why all these fell through so badly, and what
is the true straightforward way to do this if any?
Thanks in advance.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden