nazariof1985 Did a bit of research here. It's not straightforward but hopefully there is an acceptable heuristic. Seems to be used by webkit / chromium code.
The TL;DR
Use weightOfFont_
and a lookup array to convert to a CSS value:
function appKitWeightToCSSWeight(weight){
return [100,100,100,200,300,400,500,500,600,700,800,900,900,900,900,900][weight]
}
var layer = context.selection[0];
var weight = NSFontManager.sharedFontManager().weightOfFont_(layer.font());
log(appKitWeightToCSSWeight(weight));
Note : it's not 100% perfect, as weightOfFont_
doesn't seem to distinguish between Thin
and Light
font variants in my testing, but it does correctly detect Ultralight
The full story
From the Font Handling page from Apple
Font weights are typically indicated by a series of names, which can vary from font to font. Some go from Light to Medium to Bold, while others have Book, SemiBold, Bold, and Black.
This suggests using the weight name will have mixed results. Also from that page, NSFontManager
has a method weightOfFont
, which is described as
The weightOfFont: method returns an approximate ranking of a fontβs weight on a scale of 0β15, where 0 is the lightest possible weight, 5 is Normal or Book weight, 9 is the equivalent of Bold, and 15 is the heaviest possible (often called Black or Ultra Black).
So cool, we can get this weight approximation from a layer using
var layer = context.selection[0];
var weight = NSFontManager.sharedFontManager().weightOfFont_(layer.font());
but how do we convert that to a CSS weight?
After some hard googling, I came across this code in Chromium (Google Chrome), which is pulled from WebKit
int ToAppKitFontWeight(FontSelectionValue font_weight) {
float weight = font_weight;
if (weight <= 50 || weight >= 950)
return 5;
size_t select_weight = roundf(weight / 100) - 1;
static int app_kit_font_weights[] = {
2, // FontWeight100
3, // FontWeight200
4, // FontWeight300
5, // FontWeight400
6, // FontWeight500
8, // FontWeight600
9, // FontWeight700
10, // FontWeight800
12, // FontWeight900
};
DCHECK_GE(select_weight, 0ul);
DCHECK_LE(select_weight, arraysize(app_kit_font_weights));
return app_kit_font_weights[select_weight];
}
from this we can create our final algorithm