2017-04-07 86 views
1

在MacOS上塞拉利昂JavaScript進行自動化,我們可以這樣寫:JXA - 在JavaScript中獲取NSAttributedString字體度量自動化

// 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 
})(); 

回答

1

啊...這似乎是這樣做的:

(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), 
    ]); 
})();