110,499
社区成员
发帖
与我相关
我的任务
分享
using (Graphics g = this.CreateGraphics())
{
SizeF size = g.MeasureString("测试文本", new Font("宋体", 12));
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace NumberedTextBox
{
public partial class NumberedTextBoxUC : UserControl
{
public NumberedTextBoxUC()
{
InitializeComponent();
numberLabel.Font = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size + 1.019f);
}
private void updateNumberLabel()
{
//得到第一个字符和第一行
Point pos = new Point(0, 0);
int firstIndex = richTextBox1.GetCharIndexFromPosition(pos);
int firstLine = richTextBox1.GetLineFromCharIndex(firstIndex);
//得到最后一个字符和最后一行
pos.X = ClientRectangle.Width;
pos.Y = ClientRectangle.Height;
int lastIndex = richTextBox1.GetCharIndexFromPosition(pos);
int lastLine = richTextBox1.GetLineFromCharIndex(lastIndex);
//这是最后一个字符的位置,我们通过Y值计算字符长度
pos = richTextBox1.GetPositionFromCharIndex(lastIndex);
//在每一行前面加行号
numberLabel.Text = "";
for (int i = firstLine; i <= lastLine + 1; i++)
{
numberLabel.Text += i + 1 + "\n";
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
updateNumberLabel();
}
private void richTextBox1_VScroll(object sender, EventArgs e)
{
int d = richTextBox1.GetPositionFromCharIndex(0).Y % (richTextBox1.Font.Height + 1);
numberLabel.Location = new Point(0, d);
updateNumberLabel();
}
private void richTextBox1_Resize(object sender, EventArgs e)
{
richTextBox1_VScroll(null, null);
}
private void richTextBox1_FontChanged(object sender, EventArgs e)
{
updateNumberLabel();
richTextBox1_VScroll(null, null);
}
}
}
//是静态方法
static Size DataGridViewCell.MeasureTextSize(Graphics graphics,
string text,
Font font,
TextFormatFlags flags
)