3
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’ll need to know which character to overcome imageWidth
.
First, call the
Dispose()
at hand is not a good idea. Second, this method variable statement is very strange. I could be wrong, but I doubt it’s possible to determine this without an extremely complex algorithm. It would be easier if it were guaranteed that the fountain was mono-spaced.– Maniero
Thank you so much for the @bigown tips. I’m a junior dev yet, and I’d like to know what the problem is with calling
Dispose()
at hand? Is there a better alternative? What would be a mono-spaced font and how could I ensure that my string is a?– Jedaias Rodrigues
The problem of using the
Dipose()
at hand is the lack of assurance that it will be called. The best alternative is to use the blockusing
that is nothing more than atry-finally
what callDispose
. A sourcemono-espaçada é uma fonte onde todos os caracteres ocupam exatamente o mesmo espaço
.– Jéf Bueno
If there is an exception, he will not be called. http://answall.com/q/41175/101 and http://answall.com/q/22284/101. If this is not sufficient, ask a question about this. The mono font has all characters of the same width. Here it is easy to calculate the size of each one. There must be information inside the source that indicates that it is mono. I would need to search. But I don’t know if you want to guarantee this, it limits quite.
– Maniero