jxa-在JavaScript中获取NSAttributedString字体度量以实现自动化
在macOS Sierra JavaScript for Automation中,我们可以编写:jxa-在JavaScript中获取NSAttributedString字体度量以实现自动化,javascript,applescript,javascript-automation,Javascript,Applescript,Javascript Automation,在macOS Sierra JavaScript for Automation中,我们可以编写: // helvetica12Width :: String -> Num function helvetica12Width(str) { return $.NSAttributedString.alloc.init.initWithString( str ) .size.width; } 获取默认Helvetica 12中特定
// helvetica12Width :: String -> Num
function helvetica12Width(str) {
return $.NSAttributedString.alloc.init.initWithString(
str
)
.size.width;
}
获取默认Helvetica 12中特定字符串的度量。我还没有做到的是传递其他字体和字体大小的属性,并获得相应的度量
有没有人从JXA或AppleScript中发现了一种在这里有效的习惯用法/语法
更新:这是我尝试过的一种方法,但显然是不正确的,因为字体大小/名称值的变化不会影响返回值:
(() => {
'use strict';
ObjC.import('AppKit');
return $.NSAttributedString.alloc.init.initWithStringAttributes(
"Substantiation", {
'NSFontAttributeName': $.NSFont.fontWithNameSize('Helvetica', 24)
}
)
.size.width
})();
啊。。。这似乎可以做到:
(function () {
'use strict';
ObjC.import('AppKit');
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
// stringSizeInFontAtPointSize :: String -> String -> Num
// -> {width:Num, height:Num}
function stringSizeInFontAtPointSize(str, fontName, points) {
return $.NSAttributedString.alloc.init.initWithStringAttributes(
str, $({
'NSFont': $.NSFont.fontWithNameSize(fontName, points)
})
)
.size;
}
// TEST -------------------------------------------------------------------
return show([
stringSizeInFontAtPointSize("hello World", "Geneva", 32),
stringSizeInFontAtPointSize("hello World", "Geneva", 64),
stringSizeInFontAtPointSize("hello World", "Helvetica", 64),
]);
})();