如何动态更改字体大小,使文本的体积适合矩形大小?

How to change dynamically font size so the volume of text suites to rectangle size?

我编写了一个应用程序,使我能够收集有关患者的病史。问题是我写了一段代码,使我能够将文本放入矩形中,但是当文本量大于宽度和高度时,它不适合矩形大小。

问题是当文本量大于矩形尺寸时,如何动态地使字体变小?
代码:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    using (Font font1 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Point))
    {
        RectangleF rectF1 = new RectangleF(30, 30, 780, 200);
        e.Graphics.DrawString(richTextBox2.Text, font1, Brushes.Black, rectF1);
        e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1));
    }
}

正如我在评论中提到的,一种选择是继续尝试越来越小的字体,直到找到适合的字体。这不是超级有效,但如果不经常这样做,它会起作用。

// Try to find a font size that fits
int GetFontSize(string text, Graphics graphics, RectangleF rect, string fontName, int maxFontSize=32)
{
    while (maxFontSize > 6)
    {
        using (var font = new Font(fontName, maxFontSize))
        {
            var calc = graphics.MeasureString(text, font, (int)rect.Width, StringFormat.GenericTypographic);
            if (calc.Height <= rect.Height)
            {
                break;
            }
        }
        maxFontSize -= 1;
    }
    return maxFontSize;
}

示例用法:

// Helper function to draw a string and rectangle
void DrawText(Graphics graphics, string text, RectangleF rect, string fontName="Arial")
{
    int fontSize = GetFontSize(text, graphics, rect, fontName);
    using(var brush = new SolidBrush(Color.Black))
    using(var pen = new Pen(brush))
    using (var font = new Font(fontName, fontSize))
    {
        graphics.DrawString(text, font, brush, rect, StringFormat.GenericTypographic);
        graphics.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
    }
}

// Test cases
private void Form1_Paint(object sender, PaintEventArgs e)
{
    string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    RectangleF[] testCases = {
        new RectangleF(10, 10, 300, 100),
        new RectangleF(10, 120, 600, 200),
        new RectangleF(10, 330, 60, 400),
        new RectangleF(10, 330, 60, 400),
        new RectangleF(80, 330, 400, 60)
    };
    foreach (var r in testCases) {
        DrawText(e.Graphics, text, r);
    }
}

示例代码的输出: