C#GDI如何绘制适合矩形的文本?

C#GDI如何绘制适合矩形的文本?,c#,gdi,drawtext,C#,Gdi,Drawtext,我们可以很容易地在矩形内绘制文本 目前,我想画一个文本内,并适合一个矩形 请提供帮助。我认为最简单的方法是将图形输出缩放到目标矩形: public static class GraphicsExtensions { public static void DrawStringInside(this Graphics graphics, Rectangle rect, Font font, Brush brush, string text) { var textS

我们可以很容易地在矩形内绘制文本

目前,我想画一个文本内,并适合一个矩形


请提供帮助。

我认为最简单的方法是将图形输出缩放到目标矩形:

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);
    }
}

fit到底是什么意思?你想要文本与矩形具有相同的高度和宽度吗?是的,你得到了。文本字符串可能会根据矩形的高度和宽度拉伸。请发布您在第一个版本中使用的代码,以便人们向您展示如何将其调整到第二个版本。