C # system.drawing calculate font size for 1 character to fill square image

If I have System.Drawing.Bitmap with equal sizes e.g. 100x100, 50x50, and I wanted to use this code to draw a single character:

StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; font = new Font(_fontName, _fontSize, _fontStyle); GraphicsPath path = new GraphicsPath(); path.AddString("A", font.FontFamily, (int)font.Style, font.Size, rect, stringFormat); 

How can I calculate the value for _fontSize so that it fits snugly into the image?

+4
source share
2 answers

The Graphics.MeasureString function returns the line size of the given font. In a loop, you can determine which font size fits best.

http://msdn.microsoft.com/en-us/library/403ezxd2.aspx

+1
source

he will help u:

  float fontsizeem = height; int charfits=0;int line=2; for (; charfits < captchastring.Length || line < 1 ; fontsizeem--)//font support style correct // color fix { graphic.MeasureString(captchastring, new Font(fontFamily, fontsizeem, fontstyle), new SizeF((float)width*0.6f, (float)height*0.6f), format, out charfits, out line); } fontsizeem *= graphic.DpiY /72 ; // this unit converting fucks me out :((((((( path.AddString(captchastring, fontFamily,(int) fontstyle,fontsizeem,rectangle, format);// -- size 
-one
source

Source: https://habr.com/ru/post/1393585/


All Articles