Tuesday, October 26, 2010

Graphics.MeasureString (.NET C#)

After testing out various situations for scaling the font of a string to fit the text within a given Rectangle I finally settled on Graphics.MeasureString. There is a cpu hit to performing the measurement, but if you can limit the number of times you need measure it is worth it. The code below is from my Card Maker application. It handles adjusting the font size based on the size of the target Rectangle.


SizeF zSize = zGraphics.MeasureString(sInput, zFont, new SizeF(zElement.width, int.MaxValue), zFormat);
 
if (zSize.Height > zElement.height || zSize.Width > zElement.width)
{
  float newSizeRatio = 1f;
  if ((zSize.Height - zElement.height) > (zSize.Width - zElement.width))
  {
    newSizeRatio = (float)zElement.height / (float)zSize.Height;
  }
  else
  {
    newSizeRatio = (float)zElement.width / (float)zSize.Width;
  }
 
  Font scaledFont = new Font(zFont.FontFamily, newSizeRatio * zFont.Size, zFont.Style);
  zFont = scaledFont;
}

Notes:
  • zElement is an object containing the target width and height.
  • The ratio can differ due to the need to keep the text within the Rectangle. Drawing outside of the target Rectangle would defeat the purpose!
  • The int.MaxValue may seem strange but the height of the allowed Rectangle (to measure within) is not important to me. The text being tested by MeasureString is formatted to line wrap.

No comments:

Post a Comment