Get character index based on Width

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 will need to know which character is to exceed imageWidth .

    
asked by anonymous 17.11.2015 / 14:38

1 answer

2

I do not think there's anything ready for that.

My tip is: Take a letter from the text while the text is larger than the image.

Ex:

while(texto.Length > imagem.Width)
{
    texto = texto.Remove(texto.Length - 1);
}

About your question in the comment

  

Thanks for the @bigown tips. I'm still a junior dev, and I wonder what's wrong with calling Dispose () in hand? Is there a better alternative? What would be a mono-spaced font and how could I ensure that my string is one?

  • The problem with calling Dispose() on hand is that you have no guarantee that it will run. This is because in the middle of the path (between the declaration of the variable and the Dispose() ) it is possible that some exception is thrown and this will cause Dipose() not to run.

  • Yes, there is a better alternative. You can "circle" your variable in a block using , causing Dispose() to be called automatically after using it. Ex .:

    using(var objBitmap = new Bitmap(bitmapWidth, bitmapHeight))
    {
        // Ao final desse bloco, o Dispose será chamado
    }
    

    Just for the sake of curiosity, this block does exactly the same thing as

    var objBitmap = new Bitmap(bitmapWidth, bitmapHeight);
    try{
        // Fazer alguma coisa
    }finally{
        objBitmap.Dispose(); 
    }
    
  • Single-spaced fonts are fonts where all characters have exactly the same width, making it easy to calculate how much space a particular word, phrase or text will occupy.

  • 17.11.2015 / 15:01