MeasureString always thinks whitespace will fit

前端 未结 2 1485
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 22:22

I\'m trying to do some hit testing on strings (I want to get the char index from the x offset), but I\'m hitting issues with measure string.

This is essentially the cod

2条回答
  •  醉梦人生
    2021-01-23 22:40

    The problem is that the length of "abc" and "abc " are the same. Since you don't print out the trailing spaces the graphical representation is the same. I would add a character at the end and then measure the string and remove the length of the added character.

    Swith your OnPaint to this and it seems to work:

        protected override void OnPaint(PaintEventArgs e) {
            string sample = "abc                       def";
    
            e.Graphics.DrawString(sample, this.Font, Brushes.Black, PointF.Empty);
            e.Graphics.DrawLine(Pens.Red, trackBar1.Value, 0, trackBar1.Value, 100);
    
            StringFormat sf = new StringFormat(StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap | StringFormatFlags.LineLimit);
            sf.Trimming = StringTrimming.Character;
    
            var underscoreWidth = e.Graphics.MeasureString("_", this.Font).Width;
    
            for (int i = 0; i < sample.Length; i++) {
                var s = sample.Substring(0, i + 1) + "_";
                var size = e.Graphics.MeasureString(s, this.Font).Width - underscoreWidth;
                if (size > trackBar1.Value) {
                    if (s.Length > 0) {
                        var ok = s.Substring(0, s.Length - 2);
                        textBox1.Text = "[" + ok + "]";
                        base.OnPaint(e);
                        return;
                    }
                }
            }
    
            textBox1.Text = "[" + sample + "]";
            base.OnPaint(e);
        }
    

提交回复
热议问题