skip to Main Content

I am using Extendscript for Photoshop CS5 to change the text of a text layer. Is there a way of checking whether the text fits e.g. by checking whether it overflows after changing the content?

2

Answers


  1. I haven’t found a way to do this directly. But I’ve used the following technique to determine the height I needed for a textbox (I wanted to keep the width constant) before.

    • expand the textbox’s height well beyond what is needed to accommodate the text inside it.
    • duplicate the layer
    • rasterize the duplicate
    • measure the bounds of the rasterized layer.
    • adjust the bounds of the original text layer as needed
    • delete the rasterized duplicate

    Totally roundabout – but it did work.

    Login or Signup to reply.
  2. I created a solution that works perfectly fine :). Maybe someone else can use it as well. Let me know if it works for you too!

    function scaleTextToFitBox(textLayer) {     
        var fitInsideBoxDimensions = getLayerDimensions(textLayer);
    
        while(fitInsideBoxDimensions.height < getRealTextLayerDimensions(textLayer).height) {
            var fontSize = parseInt(textLayer.textItem.size);
            textLayer.textItem.size = new UnitValue(fontSize * 0.95, "px");
        }
    }
    
    function getRealTextLayerDimensions(textLayer) {
        var textLayerCopy = textLayer.duplicate(activeDocument, ElementPlacement.INSIDE);
    
        textLayerCopy.textItem.height = activeDocument.height;
        textLayerCopy.rasterize(RasterizeType.TEXTCONTENTS);
    
        var dimensions = getLayerDimensions(textLayerCopy);
        textLayerCopy.remove();
    
        return dimensions;
    }
    
    function getLayerDimensions(layer) {
        return { 
            width: layer.bounds[2] - layer.bounds[0],
            height: layer.bounds[3] - layer.bounds[1]
        };
    }
    

    How to use / Explanation

    1. Create a text layer that has a defined width and height.
    2. You can change the text layers contents and then call scaleTextToFitBox(textLayer);

    The function will change the text/font size until the text fits inside the box (so that no text is invisible)!

    The script decreases the font size by 5% (* 0.95) each step until the texts fits inside the box. You can change the multiplier to achieve a more precise result or to increase performance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search