我正在开发一个代码编辑器,希望在数字增加时自动调整标签的宽度。例如,对于1-9(1位数),有特定的宽度。然后当它达到10-99(2位数)时,标签的宽度会增加。然后再次为100-999(3位数),依此类推。
结果应该像这样:
请参考我的代码:
结果应该像这样:
请参考我的代码:
private void timer_countline_Tick(object sender, EventArgs e)
{
updateNumberLabel();
}
private void updateNumberLabel()
{
// we get index of first visible char and number of first visible line
Point pos = new Point(0, 0);
int firstIndex = rtb.GetCharIndexFromPosition(pos);
int firstLine = rtb.GetLineFromCharIndex(firstIndex);
// now we get index of last visible char and number of last visible line
pos.X = ClientRectangle.Width;
pos.Y = ClientRectangle.Height;
int lastIndex = rtb.GetCharIndexFromPosition(pos);
int lastLine = rtb.GetLineFromCharIndex(lastIndex);
// this is point position of last visible char, we'll use its Y value for calculating numberLabel size
pos = rtb.GetPositionFromCharIndex(lastIndex);
// finally, renumber label
numberLabel.Text = "";
for (int i = firstLine; i <= lastLine + 1; i++)
numberLabel.Text += i + 1 + "\n";
}
AutoSize
应该可以正常工作。没有更好的方法。 - King King