How to implement "best-fit" supplied text in a given region in image

Jun 7, 2013 at 12:07 PM
Say, I want a 100 x 100 pixel image generated, and the argument is string of dynamic length. Now, the result image should have the supplied text in best-fit size in 100 x 100 area. It should be something like 'shrink to fit' option in MS Excel.

To complicate the matter, the string have formatting also, like font-family, oblique, and other text effects.

I'm struggling for it for 2 days now.
Coordinator
Jun 7, 2013 at 7:39 PM
You could use the FontTypeMetrics method of MagickImage to calculate the size of text you are drawing. Below is a simple example for when you are trying to write a single word:
string word = "Word!";

using (MagickImage image = new MagickImage(Color.Yellow, 100, 100))
{
  image.FillColor = Color.Purple;
  image.Font = "Garamond";
  image.Density = new MagickGeometry(72, 72);
  
  image.FontPointsize = 1;
  TypeMetric typeMetric = image.FontTypeMetrics(word);
  while (typeMetric.TextWidth < image.Width)
  {
    image.FontPointsize++;
    typeMetric = image.FontTypeMetrics(word);
  }
  image.FontPointsize--;
  
  image.Annotate(word, Gravity.Center);
  image.Write("output.png");
}