user2528012
user2528012

Reputation: 89

How to scale font to fit in a specified rectangle

I want to draw a string in specified rectangle but problem is that the string with specified font may be outside the bound of rectangle.

So I want a way to scale string font to fit string in specified rectangle area.

public Font scaleFont(String text, RectangleF rect, Graphics graphics, Font pFont)
        {
            float fontSize = 20.0f;
            Font font = pFont;
            float width = graphics.MeasureString(text, pFont).Width;
            float height = graphics.MeasureString(text, pFont).Height;
            fontSize = ((rect.Width / width)  * pFont.Size);
            float heig = (rect.Height / height);
            return new Font(pFont.FontFamily, fontSize);
        }

The above code give me scaled font to fit the string in the top area of rectangle but I want to fit in whole area(Attaching out put of above algo)

Output of algo

But I want the following output.

enter image description here

Upvotes: 2

Views: 1602

Answers (1)

Anatoly Nikolaev
Anatoly Nikolaev

Reputation: 540

By fitting in whole area you means that?

enter image description here

If so, the common way is drawing a text on a bitmap and fitting one to any object you want.

To avoid pixelization, you can use your piece of code to detect best font size and best bitmap size.

Upvotes: 1

Related Questions