Найдите доступные шрифты в Adobe After Effects с помощью расширенного скрипта

В этот ответ показано, что вы можете найти шрифты, доступные для Photoshop, глядя на свойство app.fonts. Но, конечно, это не работает в After Effects, потому что Adobe.

☠☢↯†☭‼ Adobe

Есть ли способ перечислить доступные шрифты, чтобы я мог написать сценарий, который позволяет пользователю выбирать шрифт?


person stib    schedule 11.08.2019    source источник


Ответы (1)


Глядя на справку по скрипту AE, не похоже, что у AE есть способ доступа к коллекции шрифтов, как у PS и AI... При этом я придумал обходной путь для ПК с помощью After Effects system.callSystem(), чтобы передать процесс сбора шрифтов в PowerShell и использовать ScriptUI в AE, чтобы предложить пользователю сделать выбор. Для получения дополнительной информации о ScriptUI см. документ, написанный Питером Карелом здесь.

Это рабочий пример, но он был протестирован только в AE CC2019 на ПК под управлением Windows 10. В AE вам необходимо убедиться, что параметр Разрешить скриптам записывать файлы и получать доступ к сети в разделе < b>Настройки > Сценарии и выражения включены.

  1. Создайте файл powershell с именем getFonts.ps1 и сохраните его на рабочем столе (или в любом другом месте, просто не забудьте обновить файл jsx, указав новое местоположение). Затем скопируйте и вставьте следующий код:

    [System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')
    $fontList = (New-Object System.Drawing.Text.InstalledFontCollection)
    
    # save a file to the desktop with a list of all the fonts
    $fontFile = "~/Desktop/fonts.txt"
    
    # since we use Add-Content, we are appending to the file.  
    # Delete the file on run if it exists so we don't continue appending to the list
    if (Test-Path $fontFile) {
        Remove-Item $fontFile
    }
    
    # loop through the collection and write each font name to fonts.txt on the desktop
    for ($i = 0; $i -lt $fontList.Families.Length; $i++) {
        # $fontObjs.add($fontList.Families[$i].Name)
        $fontNames = $fontList.Families[$i].Name 
        Add-Content $fontFile "$fontNames"
    }
    
  2. Создайте новый файл jsx с именем textFonts.jsx. Скопируйте и вставьте следующее:

    // powershell file location
    var pathToPs1File = "~/Desktop/getFonts.ps1"
    // execute powershell file
    var fonts = system.callSystem("Powershell.exe -ExecutionPolicy Bypass " + pathToPs1File)
    
    // Give the powershell script some time (3 seconds in this case) to write all the font names
    // it may need more time if you have 1000s of fonts, adjust as needed
    $.sleep(3000)
    
    // function to parse through the fonts pulled from the text file
    // will return array of font names for ScriptUI
    function getAllFonts(fontsFromFile) {
    
        fontsFromFile = fontsFromFile.split("\n");
        var fontListForScriptUI = []
        for (i = 0; i < fontsFromFile.length; i++) {
            if (!fontsFromFile[i]) {
                continue;
            }
            else {
                fontListForScriptUI.push(fontsFromFile[i])
            }
        }
        return fontListForScriptUI;
    }
    
    // Script UI will return the *name* of the font chosen.
    function main() {
    
        //surpress error dialogs
        app.beginSuppressDialogs()
        var scriptVersion = 1.0;
    
        var fontFile = File("~/Desktop/fonts.txt");
    
        fontFile.open("e")
        var fontList = fontFile.read();
        fontFile.close();
    
        var allFonts = getAllFonts(fontList);
    
        //////////////////////////////////////////////////////////////////////////
        //
        // Options Dialog
        //
        //////////////////////////////////////////////////////////////////////////
    
        var options = new Window('dialog', 'Test Script ' + scriptVersion);
            options.alignChildren = ['fill', 'top'];
            options.graphics.font = ScriptUI.newFont ("Segoe UI", "Regular", 14);
    
        if (app.version == "13.0.1") { // if its CS6, font color is dark, otherwise font color is light
            options.graphics.foregroundColor = options.graphics.newPen (options.graphics.PenType.SOLID_COLOR, [0.2, 0.2, 0.2], 1);
        }
        else {
            options.graphics.foregroundColor = options.graphics.newPen (options.graphics.PenType.SOLID_COLOR, [1,1,1,], 1);
        }
    
        //////////////////////////////////////////////////////////////////////////
        // List Font Names
        //////////////////////////////////////////////////////////////////////////
    
        var groupOptions = options.add('panel', undefined, 'Font Picker');
            groupOptions.orientation = 'column';
            groupOptions.alignChildren = 'left';
            groupOptions.margins = 30;
            groupOptions.indent = 30;
            groupOptions.graphics.font = ScriptUI.newFont ("Segoe UI", "Regular", 14);
    
            groupOptions.add('statictext', undefined, 'System Fonts:');
    
        var fontList = groupOptions.add('dropdownlist', undefined, allFonts);
            fontList.preferredSize.width = 300;
    
        //////////////////////////////////////////////////////////////////////////
        // OK & Cancel Buttons
        //////////////////////////////////////////////////////////////////////////
    
        var btns = options.add('group {alignment: "right" }');
            btns.orientation = 'row';
        var okButton = btns.add('button', undefined, 'OK', { name: 'ok' });
        var canButton = btns.add('button', undefined, 'Cancel', { name: 'cancel' });
    
        var myResult = options.show();
    
        if (myResult == 2) {
            // on cancel, alert the user and exit the script
            alert("Operation Canceled!");
            exit(0);
        }
    
        options.close();
        return fontList.selection.text
    }
    
    // store the returned value for later as pickedFont
    var pickedFont = main();
    
    alert(pickedFont);
    

Наконец, запустите файл jsx в AE.

person InternetRebel    schedule 11.08.2019
comment
Спасибо. Я надеялся, что мне не придется использовать оболочку — тем более, что пользователи этого скрипта кроссплатформенные, — но похоже, что это единственный способ. - person stib; 12.08.2019
comment
Вот команда Powershell, которую я использовал — поскольку Powershell имеет встроенную функцию convertTo-json, гораздо проще просто преобразовать объект InstallFontCollection в json и сохранить его, а затем на языке, который вы можете легко прочитать в своем сценарии: [System.Reflection.Assembly]::LoadWithPartialName('System.Drawing'); (convertTo-json(New-Object System.Drawing.Text.InstalledFontCollection))>$env:temp\fontlist.txt - person stib; 16.08.2019