Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 219807
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T18:52:46+00:00 2026-05-11T18:52:46+00:00

I just wrote some code to scale a font to fit within (the length

  • 0

I just wrote some code to scale a font to fit within (the length of) a rectangle. It starts at 18 width and iterates down until it fits.

This seems horribly inefficient, but I can’t find a non-looping way to do it.
This line is for labels in a game grid that scales, so I can’t see a work-around solution (wrapping, cutting off and extending past the rectangle are all unacceptable).

It’s actually pretty quick, I’m doing this for hundreds of rectangles and it’s fast enough to just slow it down a touch.

If nobody comes up with anything better, I’ll just load the starting guess from a table (so that it’s much closer than 18) and use this–except for the lag it works great.

public Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
    float nextTry=18.0f;
    Font font=pFont;

    while(x > 4) {                             
            font=g.getFont().deriveFont(nextTry);
            FontMetrics fm=g.getFontMetrics(font);
            int width=fm.stringWidth(text);
            if(width <= rect.width)
                return font;
            nextTry*=.9;            
    }
    return font;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T18:52:46+00:00Added an answer on May 11, 2026 at 6:52 pm

    Semi-pseudo code:

    public Font scaleFont(
        String text, Rectangle rect, Graphics g, Font font) {
        float fontSize = 20.0f;
    
        font = g.getFont().deriveFont(fontSize);
        int width = g.getFontMetrics(font).stringWidth(text);
        fontSize = (rect.width / width ) * fontSize;
        return g.getFont().deriveFont(fontSize);
    }
    

    A derivation that iterates:

    /**
     * Adjusts the given {@link Font}/{@link String} size such that it fits
     * within the bounds of the given {@link Rectangle}.
     *
     * @param label    Contains the text and font to scale.
     * @param dst      The bounds for fitting the string.
     * @param graphics The context for rendering the string.
     * @return A new {@link Font} instance that is guaranteed to write the given
     * string within the bounds of the given {@link Rectangle}.
     */
    public Font scaleFont(
        final JLabel label, final Rectangle dst, final Graphics graphics ) {
      assert label != null;
      assert dst != null;
      assert graphics != null;
    
      final var font = label.getFont();
      final var text = label.getText();
    
      final var frc = ((Graphics2D) graphics).getFontRenderContext();
    
      final var dstWidthPx = dst.getWidth();
      final var dstHeightPx = dst.getHeight();
    
      var minSizePt = 1f;
      var maxSizePt = 1000f;
      var scaledFont = font;
      float scaledPt = scaledFont.getSize();
    
      while( maxSizePt - minSizePt > 1f ) {
        scaledFont = scaledFont.deriveFont( scaledPt );
    
        final var layout = new TextLayout( text, scaledFont, frc );
        final var fontWidthPx = layout.getVisibleAdvance();
    
        final var metrics = scaledFont.getLineMetrics( text, frc );
        final var fontHeightPx = metrics.getHeight();
    
        if( (fontWidthPx > dstWidthPx) || (fontHeightPx > dstHeightPx) ) {
          maxSizePt = scaledPt;
        }
        else {
          minSizePt = scaledPt;
        }
    
        scaledPt = (minSizePt + maxSizePt) / 2;
      }
    
      return scaledFont.deriveFont( (float) Math.floor( scaledPt ) );
    }
    

    Imagine you want to add a label to a component that has rectangular bounds r such that the label completely fills the component’s area. One could write:

    final Font DEFAULT_FONT = new Font( "DejaVu Sans", BOLD, 12 );
    final Color COLOUR_LABEL = new Color( 33, 33, 33 );
    
    // TODO: Return a valid container component instance.
    final var r = getComponent().getBounds();
    final var graphics = getComponent().getGraphics();
    
    final int width = (int) r.getWidth();
    final int height = (int) r.getHeight();
    
    final var label = new JLabel( text );
    label.setFont( DEFAULT_FONT );
    label.setSize( width, height );
    label.setForeground( COLOUR_LABEL );
    
    final var scaledFont = scaleFont( label, r, graphics );
    label.setFont( scaledFont );
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 357k
  • Answers 357k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The other answers are correct. Here is some code you… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer you ruin the noConflict concept by reassigning the jquery to… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer If you get that particular error, you don't actually have… May 14, 2026 at 9:40 am

Related Questions

No related questions found

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.