MeasureString始终认为空格适合 [英] MeasureString always thinks whitespace will fit

查看:103
本文介绍了MeasureString始终认为空格适合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对字符串进行命中测试(我想从x偏移量获取char索引),但是我遇到了度量字符串的问题.

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 code I am using

     StringFormat sf = new StringFormat(StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap | StringFormatFlags.LineLimit);
     e.Graphics.MeasureString("test    string", this.Font, new SizeF(xHitTestPosition, this.Font.Height), sf, out charFitted, out linesFilled);

应该将charFitted的值设置为它可以容纳的字符数(我根据尝试击中的点给它一个大小).

The value of charFitted should be set to the number of chars it could fit within the size its give (I'm giving it a size based on the point I am trying to hit test).

这很好,直到区域足够大以容纳测试"字符串为止.此时,charFitted从3("tes")跳到8("test").基本上,它总是包含所有空白,而不管它给定了多少空白.

This works fine until the area is large enough to hold the 'test' string. at this point charFitted jumps from 3 ('tes') to 8 ('test '). It basically always includes all the whitespace regardless of the space it has been give.

我尝试弄乱StringFormat设置,但似乎无济于事...

I've tried messing around with the StringFormat settings, but nothing seems t help...

我已包含一个演示以下内容的测试应用程序

I've included a test app bellow that demonstrates this

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            trackBar1.Maximum = this.ClientRectangle.Width;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            string sample = "abc                       def";
            int charFitted, linesFilled;

            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;
            e.Graphics.MeasureString(sample, this.Font, new SizeF(trackBar1.Value, this.Font.Height), sf, out charFitted, out linesFilled);
            textBox1.Text = "[" + sample.Substring(0, charFitted) + "]";

            base.OnPaint(e);
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            Invalidate();
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.trackBar1 = new System.Windows.Forms.TrackBar();
            this.textBox1 = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
            this.SuspendLayout();
            // 
            // trackBar1
            // 
            this.trackBar1.Location = new System.Drawing.Point(13, 184);
            this.trackBar1.Name = "trackBar1";
            this.trackBar1.Size = new System.Drawing.Size(259, 45);
            this.trackBar1.TabIndex = 0;
            this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(22, 229);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(237, 20);
            this.textBox1.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.trackBar1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TrackBar trackBar1;
        private System.Windows.Forms.TextBox textBox1;
    }
}

推荐答案

问题是"abc"和"abc"的长度相同.由于您没有打印出尾随空格,因此图形表示是相同的. 我会在末尾添加一个字符,然后测量字符串并删除添加的字符的长度.

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.

将此与您的OnPaint一起使用,看来可行:

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);
    }

这篇关于MeasureString始终认为空格适合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆