简体   繁体   中英

Measure the amount of characters a RichTextBox can have on a line

Given a C# Winforms RichTextBox I would like to know how many characters I can fit on a line. I know what my Font (monospaced characters) and FontSize are.

Cheers, Sean

If your font is monospace, just divide the text box width by the width of one char as measured by Graphics.MeasureString :

static int GetWidthInChars(int widthInPixels, Font font, Graphics g)
{
    return (int) (widthInPixels / g.MeasureString ("a", font).Width);
}

I noticed that measuring one character adds some extra space which inadequately represents the real width of one character.

private int CalculateMaxDescriptionLineLength()
{
    Graphics g = _tb.CreateGraphics();
    float twoCharW = g.MeasureString("aa", _tb.Font).Width;
    float oneCharW = g.MeasureString("a", _tb.Font).Width;
    return (int)((float)_tb.Width / (twoCharW - oneCharW));
}

Thanks Sergey for putting me on the right path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM