I have the following method to calculate the width of a text:
public float GetWidthOfString(string str, Font font, int bitmapWidth, int bitmapHeight)
{
Bitmap objBitmap = default(Bitmap);
Graphics objGraphics = default(Graphics);
objBitmap = new Bitmap(bitmapWidth, bitmapHeight);
objGraphics = Graphics.FromImage(objBitmap);
SizeF stringSize = objGraphics.MeasureString(str, font);
objBitmap.Dispose();
objGraphics.Dispose();
return stringSize.Width;
}
To use the method, simply:
var font = new Font("Arial", 50, FontStyle.Bold);
var texto = "Stackoverflow em Português";
var textoWidth = GetWidthOfString(texto, font, imageWidth, imageHeight);
Imagine that imageWidth = 644
, but the result in textoWidth
is greater than 644
. Then I will need to know which character is to exceed imageWidth
.