Dynamically resizing font to fit space while using Graphics.DrawString

前端 未结 5 1888
北荒
北荒 2020-12-08 16:10

Does anyone have a tip whereas you could dynamically resize a font to fit a specific area? For example, I have an 800x110 rectangle and I want to fill it with the max size f

5条回答
  •  隐瞒了意图╮
    2020-12-08 16:51

    Here is my solution that support wrapping.

    public static Font GetAdjustedFont(Graphics graphic, string str, Font originalFont, Size containerSize)
        {
            // We utilize MeasureString which we get via a control instance           
            for (int adjustedSize = (int)originalFont.Size; adjustedSize >= 1; adjustedSize--)
            {
                var testFont = new Font(originalFont.Name, adjustedSize, originalFont.Style, GraphicsUnit.Pixel);
    
                // Test the string with the new size
                var adjustedSizeNew = graphic.MeasureString(str, testFont, containerSize.Width);
    
                if (containerSize.Height > Convert.ToInt32(adjustedSizeNew.Height))
                {
                    // Good font, return it
                    return testFont;
                }
            }
    
            return new Font(originalFont.Name, 1, originalFont.Style, GraphicsUnit.Pixel);
        }
    

    How to use:

    var font = GetAdjustedFont(drawing, text, originalfont, wrapSize);
    drawing.DrawString(text, font, textBrush, new Rectangle(0, 0, wrapSize.Width, wrapSize.Height));
    

提交回复
热议问题