简体   繁体   中英

C# GDI How to draw text to fit in rectangle?

We can draw a text inside a rectangle easily.

在此处输入图片说明

Currently I would like to draw a text inside and FIT a rectangle.

在此处输入图片说明

Please help.

I think the easiest way is to scale the graphics output to the destination rectangle:

public static class GraphicsExtensions
{
    public static void DrawStringInside(this Graphics graphics, Rectangle rect, Font font, Brush brush, string text)
    {
        var textSize = graphics.MeasureString(text, font);
        var state = graphics.Save();
        graphics.TranslateTransform(rect.Left, rect.Top);
        graphics.ScaleTransform(rect.Width / textSize.Width, rect.Height / textSize.Height);
        graphics.DrawString(text, font, brush, PointF.Empty);
        graphics.Restore(state);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM