Yoav
Yoav

Reputation: 6098

10.9 replacement for [NSFont systemFontOfSize: weight:]

I would like to implement a replacement method for [NSFont systemFontOfSize:13 weight:NSFontWeightLight] that works on Mac OS 10.9 and 10.10.

I can get the font descriptor by [[NSFont systemFontOfSize:13] fontDescriptor].

However, I could not figure out how to change the font descriptor weight and create an NSFont from it.

As explained in WWDC 2015, #804 : 30:17, we should not take the family name from the system font (as suggested here and here).

Is it possible to change the font descriptor weight and get a new NSFont from it?

Upvotes: 4

Views: 1709

Answers (2)

mangerlahn
mangerlahn

Reputation: 4966

This is probably not the answer, just a hint for OS X 10.10. [NSFont systemFontOfSize: weight:] can be used under OS X 10.10 and works fine. I have not tried this under 10.9 though. I am not sure where I heard this, but I thought that this method is backward compatible with older releases.

I asked an AppKit engineer at WWDC about this and he was surprised that my app worked under 10.10 with the new API. However, he did not recommend me to use the API on older systems like 10.10 because it may use private API in the background that prevents apps from being accepted by the MAS.

Upvotes: 0

Ken Thomases
Ken Thomases

Reputation: 90571

I can think of two ways, but neither gives exactly the same semantics as +[NSFont systemFontOfSize:weight:].

One is to use -[NSFontManager convertWeight:ofFont:]. That just allows you to go up or down in weight, not select a specific target weight. However, if it provides a new font, you can query -[NSFontManager weightOfFont:] to get its weight, where a value of 3 is "light" (see the table at -convertWeight:ofFont:). By repeating the process, you may be able to get the weight you want, although the method could fail or overshoot.

The other is to go from font to font descriptor to new font descriptor with the desired weight to a new font:

NSFontDescriptor* origDescriptor = origFont.fontDescriptor;
NSFontDescriptor* newDescriptor = [origDescriptor fontDescriptorByAddingAttributes:@{ NSFontTraitsAttribute: @{ NSFontWeightTrait: @(-0.2) } }];
NSFont* newFont = [NSFont fontWithDescriptor:newDescriptor size:origFont.pointSize];

Here I just chose -0.2 arbitrarily. The problem with this approach is that it takes weights as values from -1.0 to 1.0, with 0 as "normal". It's not clear how to map that scale to "light weight". I suppose you can query some light weight fonts you acquire by name to see what their weights are.

Upvotes: 2

Related Questions