OnFontChange method
本文关键字:method OnFontChange | 更新日期: 2023-09-27 18:33:29
我有我的控件MyLabel,当我更改字体大小时,必须在构造函数中执行此代码。如何使此代码工作?
protected override void OnFontChanged(EventArgs e)
{
if (AutoSize_)
{
this.AutoSize = true;
remember_size = this.Size;
this.AutoSize = false;
this.Size = new Size(remember_size.Width, remember_size.Height);
remember_size = this.Size;
}
...
this.Invalidate();
}
但是不要工作。例如,此代码工作:
protected override void OnFontChanged(EventArgs e)
{
if (AutoSize_)
{
this.AutoSize = true;
}
...
this.Invalidate();
}
如果您的目标是调整标签的大小,以便文本可见,而不管字体大小如何,AutoSize 属性将为您执行此操作。但是,如果您出于某种原因希望使用自己的代码处理此问题,则可以尝试将 AutoSize 属性设置为 false(并且不更改它......
可以从任何窗体、用户控件或控件调用下面的代码方法。 它将以指定字体返回指定文本的大小。
public static Size MeasureText(Graphics graphicsDevice, String text, Font font)
{
System.Drawing.SizeF textSize = graphicsDevice.MeasureString(text, font);
int width = (int)Math.Ceiling(textSize.Width);
int heigth = (int)Math.Ceiling(textSize.Height);
Size size = new Size(width, heigth);
return size;
}
现在,您需要检查标签是否未超出父容器,这会导致某些标签文本被截断。 如下所示的操作将完成此操作:
private void ResizeParentAccordingToLabelSize(Label resizedLabel)
{
int necessaryWidth = resizedLabel.Location.X + resizedLabel.Width;
int necessaryHeight = resizedLabel.Location.Y + resizedLabel.Height;
if (necessaryWidth > this.Width)
{
this.Width = necessaryWidth;
}
if (necessaryHeight > this.Height)
{
this.Height = necessaryHeight;
}
}