#Proper methods to Scale and Align text within a rectangle.

1 messages · Page 1 of 1 (latest)

signal marsh
#
    private void scaleFont(Graphics2D g) {
        textSize = maxTextSize;
        font = new Font(fontName, Font.BOLD, textSize);
        metrics = g.getFontMetrics(font);
        textSize = Math.max(minTextSize, Math.min(maxTextSize, (int) (textSize *  Math.min((width - width * 0.04) / metrics.stringWidth(text), (double) height / metrics.getHeight()))));
        font = font.deriveFont(Font.BOLD, textSize);
        alignText(g.getFontMetrics(font));
    }

    private void alignText(FontMetrics metrics) {
        textX = x+(width*alignX);
        textY = y+(height*alignY);
        textWidth = metrics.stringWidth(text)/2;
        textHeight = metrics.getAscent()/2;
        textTransform.setToTranslation(  Math.floor((textX-textWidth)/2+0.5)*2  , Math.floor((textY+textHeight)/2+0.5)*2  );
        textOutline = new TextLayout(text, font, metrics.getFontRenderContext()).getOutline(textTransform);
    }```


im using pure java.awt to draw and fill a textoutline, 

`x,y,width,height` represents the rectangle.
`alignX` and `alignY` are numbers between 0 and 1 representing the percentage of width and height. (this can be used to align text to the center,top,bottom,left and right.

`alignText()` is probably as good as its gonna get, maybe.
`scaleFont()` seems very improper to me because i have to set textSize to maxTextSize and then create two fonts... but its the only method i could come up with right now.

So what would be a better way to go about scaling the font? while maintaining speed.
tawny sorrelBOT
#

<@&987246399047479336> please have a look, thanks.

ancient hill
#

if you want to warp font, you can draw the font to an image & adjust the width & height. although know that it could affect visuals

signal marsh
#

it'll increase/decrease in size based on the rectangle size. (which can also be resized in a linear manner or directly set to a certain size)
that being said the text can't just increase or decrease arbitrarily , it has to position/scale relative to the rectangle in one frame.

#

what i have right now works fine, but its a tad bit off and also just seems like im overcomplicating the scaling a bit, code wise.

ancient hill
#

whats off about it? how it loses height when sized horizontally?

signal marsh
signal marsh
#

will help me with wrapping later as well.

#

here is the vertical rescale.