Dynamically resizing font to fit space while using Graphics.DrawString

前端 未结 5 1902
北荒
北荒 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 17:06

    I don't want to bash against saaeds solution which is probably pretty awesome, too. But I found another one on msdn: Dynamic Graphic Text Resizing which worked for me.

    public Font GetAdjustedFont(Graphics GraphicRef, string GraphicString, Font OriginalFont, int ContainerWidth, int MaxFontSize, int MinFontSize, bool SmallestOnFail)
    {
       // We utilize MeasureString which we get via a control instance           
       for (int AdjustedSize = MaxFontSize; AdjustedSize >= MinFontSize; AdjustedSize--)
       {
          Font TestFont = new Font(OriginalFont.Name, AdjustedSize, OriginalFont.Style);
    
          // Test the string with the new size
          SizeF AdjustedSizeNew = GraphicRef.MeasureString(GraphicString, TestFont);
    
          if (ContainerWidth > Convert.ToInt32(AdjustedSizeNew.Width))
          {
           // Good font, return it
             return TestFont;
          }
       }
    
       // If you get here there was no fontsize that worked
       // return MinimumSize or Original?
       if (SmallestOnFail)
       {
          return new Font(OriginalFont.Name,MinFontSize,OriginalFont.Style);
       }
       else
       {
          return OriginalFont;
       }
    }
    

提交回复
热议问题