测量Courier字符宽度以填充列表框

时间:2014-06-17 12:17:45

标签: c# string graphics fonts

我正在尝试编写一个给出描述的方法,并且标记将返回填充字符串中填充行的填充字符串。我以为我可能已经使用了当前的代码,但我注意到它高估了Graphics.MeasureString(...)字符的宽度。经过一番挖掘后,我发现MeasureString以枚举GraphicsUnits为单位PageUnits返回其值。

下面是我创建的SSCCE来显示我的问题。我不确定如何将给定的PageUnit转换为像素。有什么想法吗?

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 StringPadProj
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            theListBox.Items.Add(getPaddedStr("meow", "[Cat]"));
            theListBox.Items.Add(getPaddedStr("woof", "[Dog]"));
            theListBox.Items.Add(getPaddedStr("chirp", "[Bird]"));
            theListBox.Items.Add(getPaddedStr("cricket", "[Cricket]"));
        }

        private String getPaddedStr(String desc, String tag)
        {
            int availSpacePx = theListBox.Width;
            Console.Out.WriteLine("ListBoxW: " + availSpacePx);
            Graphics e = theListBox.CreateGraphics();
            e.PageUnit = GraphicsUnit.Pixel;
            Font listBFont = theListBox.Font;
            SizeF charSize = e.MeasureString("k", listBFont);
            Console.Out.WriteLine("CharSize: " + charSize);
            int numCharPerLine = (int)Math.Floor(availSpacePx / charSize.Width);
            Console.Out.WriteLine("CharsPerLine: " + numCharPerLine);

            int tagLen = tag.Length;
            int spaceLeft = numCharPerLine - tagLen;
            if (desc.Length > spaceLeft)
                desc = desc.Substring(0, spaceLeft);
            else if (desc.Length < spaceLeft)
                while (desc.Length < spaceLeft)
                    desc += " ";
            String itemText = desc + tag;

            return itemText;
        }

        /// <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.theListBox = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            // 
            // theListBox
            // 
            this.theListBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.theListBox.FormattingEnabled = true;
            this.theListBox.ItemHeight = 14;
            this.theListBox.Location = new System.Drawing.Point(12, 12);
            this.theListBox.Name = "theListBox";
            this.theListBox.Size = new System.Drawing.Size(350, 172);
            this.theListBox.TabIndex = 0;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(374, 198);
            this.Controls.Add(this.theListBox);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ListBox theListBox;
    }
}

编辑:

所以似乎MeasureString(...)正在做它应该做的事情。据我所知,问题在于theListBox.Width值的单位。似乎它们不是以像素为单位测量的。我实际上找不到任何引用Control.Width单位的确切内容。

现在的问题是,如何将Control.Width的单位转换/找到像素?

1 个答案:

答案 0 :(得分:1)

编辑:新答案:

MeasureString上的MSDN说明了一切:

  

MeasureString方法设计用于单个字符串   并包括字符串前后的少量额外空间   允许悬垂的字形。此外,DrawString方法调整   字形指向优化显示质量并可能显示字符串   比MeasureString报告的要窄。获得适合的指标   对于布局中的相邻字符串(例如,实现时)   格式化文本),使用MeasureCharacterRanges方法或其中之一   MeasureString方法,它接受StringFormat并传递   GenericTypographic。另外,请确保TextRenderingHint   图形是AntiAlias。

因此,将measure命令更改为类似的命令将获得适合乘以的单个字符的度量(当使用等宽字体时):

SizeF charSize = e.MeasureString("k", listBFont, 
                                 PointF.Empty, StringFormat.GenericTypographic);
相关问题