In macOS Sierra JavaScript for Automation, we can use the following code snippet to retrieve metrics for a specific string in the default Helvetica 12 font:
// helvetica12Width :: String -> Num
function helvetica12Width(str) {
return $.NSAttributedString.alloc.init.initWithString(
str
)
.size.width;
}
However, I have been struggling to pass in attributes for different fonts and sizes to obtain corresponding metrics. Has anyone found a solution using JXA or AppleScript?
Update: I have attempted an approach, but it does not seem to produce the desired results as changes in font size/name do not affect the output:
(() => {
'use strict';
ObjC.import('AppKit');
return $.NSAttributedString.alloc.init.initWithStringAttributes(
"Substantiation", {
'NSFontAttributeName': $.NSFont.fontWithNameSize('Helvetica', 24)
}
)
.size.width
})();