.Net Compact Framework: Texthöhe berechnen

24. Juli 2009

dotnet
Leider gibt es im .Net Compact Framework keine native Methode, um die benötigte Höhe eines Textes zu berechnen, welcher eine feste Breite hat. Graphics.MeasureString() funktioniert leider nur ohne Breitenangabe und liefert daher die Höhe und Breite einer Zeile zurück. Um dennoch an die Höhe eines Textes zu kommen, hab ich mir folgende Helfermethode geschrieben:

public static float GetTextHeight(int width, string text, Font font, Graphics graphics)
{
    // Leerer String
    if (string.IsNullOrEmpty(text))
        return 0;
 
    SizeF wordSize = new SizeF();
    SizeF spaceSize = graphics.MeasureString(" ", font);
 
    string[] parts = text.Split(' ');
    float tmpWidth = 0;
    int rows = 1;
 
    for(int i = 0; i < parts.Length; i++)
    {
        wordSize = graphics.MeasureString(parts[i], font);
 
        // Word passt noch in aktuelle Zeile
        if (tmpWidth + wordSize.Width + spaceSize.Width <= width)
        {
            tmpWidth += wordSize.Width + spaceSize.Width;
        }
        // Neue Zeile anfangen
        else
        {
            // Wort passt ohne Leerzeichen noch in alte Zeile
            if (tmpWidth + wordSize.Width <= width)
            {
                if(i == parts.Length - 1)
                    continue;
 
                tmpWidth = 0;
            }
            // Word in neue Zeile setzten
            else
                tmpWidth = wordSize.Width + spaceSize.Width;
 
            rows++;
        }
    }
 
    return rows * wordSize.Height;
}

Schreib einen Kommentar

Previous post:

Next post: