2017-04-07 1 views
1

Dans macOS Sierra JavaScript pour l'automatisation, nous pouvons écrire:JXA - Obtenir des mesures de police NSAttributedString en JavaScript pour l'automatisation

// helvetica12Width :: String -> Num 
function helvetica12Width(str) { 
    return $.NSAttributedString.alloc.init.initWithString(
      str 
     ) 
     .size.width; 
} 

pour obtenir des mesures pour une chaîne particulière dans la valeur par défaut Helvetica 12. Ce que je n'ai pas encore réussi à faire est de transmettre des attributs pour d'autres polices et tailles de police, et obtenir des mesures correspondantes pour ceux-ci.

Est-ce que quelqu'un a découvert un idiome/syntaxe qui fonctionne ici à partir de JXA ou AppleScript?

Mise à jour: C'est le genre de chose que j'ai expérimenté avec - bien loin du compte cependant, comme la variation de la taille des caractères/valeurs de nom ne modifie pas la valeur de retour:

(() => { 
    'use strict'; 

    ObjC.import('AppKit'); 

    return $.NSAttributedString.alloc.init.initWithStringAttributes(
      "Substantiation", { 
       'NSFontAttributeName': $.NSFont.fontWithNameSize('Helvetica', 24) 
      } 
     ) 
     .size.width 
})(); 

Répondre

1

Ah ... cela semble le faire:

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