简体   繁体   中英

Strange FontSize change

I've encountered a strange thing today, working with .

I've created a RichTextBox with default FontSize of 14.25 pt.

I was performing some operation and I needed to create temporary RichTextBox to which I have copied selected text fromy my original RichtextBox . After that, without no changes made by me, the whole tempRichTextBox text's font size increased exactly 0.25 pt . Every single letter. Is that some bug or what?

using (RichTextBox tempRichTextBox = new RichTextBox())
{
    tempRichTextBox.Rtf = this.richTextBox.SelectedRtf;
    int tempStart = this.richTextBox.SelectionStart;
    int tempLength = this.richTextBox.SelectionLength;
    for (int i = 0; i < tempLength; i++)
    {
        tempRichTextBox.Select(i, 1);
        this.baseSize = tempRichTextBox.SelectionFont.Size;
    }
    tempRichTextBox.Select(0, tempLength);
    this.richTextBox.SelectedRtf = tempRichTextBox.SelectedRtf;
    this.richTextBox.Select(tempStart, tempLength);
}

Does anybody has an idea why is that happening?

I found that WinForms adds to font size (or sometimes subtracts from it) 0.25 . You see 14.25 in designer, but it is achieved because value 14 was initially stored there. I saw that happening also when playing with FontDialog system dialog alone. You choose font size 8 and in returned Font object you find 8.25. On some sizes I have found things like 14.75 instead of 15. But it is not growing with font size, ie you will find the same small differences with font size = 5000.

Cause: font size is changing in steps of 0.75. It is related to DPI and font size units.

So implement formula taking that into account and you should start getting more expectable results. Just note that DPI or font size units can be different in context of FontDialog and RTB.

That is interesting. I don't have an answer as to why, but the differences repeat every 3 pt font sizes.

void btn_Click(object sender, EventArgs e) {
    StringBuilder sb = new StringBuilder();
    richTextBox.Text = "asdf";
    for (int i = 24; i <= 100; i++) {
        using (Font f = new Font(SystemFonts.DefaultFont.FontFamily, 1f * i / 4)) {
            richTextBox.SelectAll();
            richTextBox.SelectionFont = f;
            richTextBox.Font = f;
            sb.AppendLine(f.Size + "\t" + richTextBox.SelectionFont.Size + "\t" + Math.Round(f.Size - richTextBox.SelectionFont.Size, 3));
        }
    }
}

在此输入图像描述

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