C#中如何获取一个字体的宽度值(像素单位)
应用:减去了一个空格的长, 字符间距还是有点差距
private void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
if (e.Index > -1) {
e.DrawBackground();
Graphics g = e.Graphics;
List<string> splitRes = StringUtil.SplitGetAll(textBox1.Text, listBox1.Items[e.Index].ToString());
// Console.WriteLine(string.Join("-", splitRes));
// e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
float spaceWidth = e.Graphics.MeasureString(" ", new Font("宋体", 12)).Width;
float x = 0;
for (int i = 0; i < splitRes.Count(); i++) {
if (textBox1.Text == splitRes[i]) {
e.Graphics.DrawString(splitRes[i], e.Font, Brushes.Red, new PointF(x, e.Bounds.Y), StringFormat.GenericDefault);
} else {
e.Graphics.DrawString(splitRes[i], e.Font, Brushes.Black, new PointF(x, e.Bounds.Y), StringFormat.GenericDefault);
}
x += e.Graphics.MeasureString(splitRes[i], new Font("宋体", 12)).Width - spaceWidth;
}
e.DrawFocusRectangle();
}
}
是不是这个意思
private void button1_Click(object sender, EventArgs e) {
Graphics g = this.CreateGraphics();
SizeF sizeF = g.MeasureString("A", new Font("宋体", 9));
MessageBox.Show(sizeF.Width + " " + sizeF.Height);
g.Dispose();
}
c# 获得文字的像素宽度
Graphics graphics = CreateGraphics();
SizeF sizeF = graphics.MeasureString(textBox1.Text, new Font("宋体", 9));
MessageBox.Show(string.Format("字体宽度:{0},高度:{1}", sizeF.Width, sizeF.Height));
graphics.Dispose();
使用g.MeasureString()获得
使用MeasureString测量出来的字符宽度,总是比实际宽度大一些,而且随着字符的长度增大,貌似实际宽度和测量宽度的差距也越来越大了。查了一下MSDN,找到了下面这个理由:
MeasureString 方法旨在与个别字符串一起使用,它在字符串前后包括少量额外的空格供突出的标志符号使用。
string str;
str = "大";
Font f = new Font("SimSun", 7F, System.Drawing.FontStyle.Regular);
Graphics g = this.CreateGraphics();
//单位为mm
g.PageUnit = GraphicsUnit.Millimeter;
SizeF sim = g.MeasureString(str, f);
2、使用TextRenderer.MeasureText获得,提供使用指定尺寸创建文本初始边框时,使用指定的设备上下文、字体和格式说明所绘制的指定文本的尺寸(以像素为单位)。这个好像更长
private void MeasureText(PaintEventArgs e) {
string str;
str = "大家好";
Font f = new Font("SimSun", 7F, System.Drawing.FontStyle.Regular);
Size sif = TextRenderer.MeasureText(e.Graphics, str, f, new Size(0, 0), TextFormatFlags.NoPadding);
MessageBox.Show((sif.Width / pdi).ToString());
}
private void print(object sender, PaintEventArgs e)
{
MeasureText(e);
}
谢谢推荐! 关