问题描述
我有一个自定义的Label类,绘制的文本不适合.我在这里做什么错了?
I have a custom Label class, drawn text doesn't fits. What am I doing wrong here?
class MyLabel: Label
{
public MyLabel()
{
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.Black, Color.LightGray, LinearGradientMode.ForwardDiagonal))
e.Graphics.DrawString(Text, Font, brush, ClientRectangle);
}
}
如果我将MyLabel的文本设置为"123456790 123456790"( AutoSize = true ),那么我会在Designer中(或在运行时)看到"1234567890 123456789"(没有最后一个零,但是一些空间).如果我尝试使用"1234567890 1234567890 1234567890 1234567890",则将出现"1234567890 1234567890 1234567890 12345678"(不包含"90",但还会有一些空格).
If I set text of MyLabel to be "123456790 123456790" (AutoSize = true), then I see in Designer (or at run-time) "1234567890 123456789 " (no last zero, but some space). If I try "1234567890 1234567890 1234567890 1234567890", then there will be "1234567890 1234567890 1234567890 12345678 " (no "90", but again some space).
推荐答案
此处介绍了上述问题的一种解决方案(可能不是最好的解决方案),可以将其重新表述为带有渐变文本颜色的自动调整大小的标签".
Here goes a solution (possible not the best one) to the described problem which can be rephrased as "Autosized Label with Graditent text color".
class MyLabel: Label
{
private bool _autoSize = true;
/// <summary>
/// Get or set auto size
/// </summary>
public new bool AutoSize
{
get { return _autoSize; }
set
{
_autoSize = value;
Invalidate();
}
}
public MyLabel()
{
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
base.AutoSize = false;
}
protected override void OnPaint(PaintEventArgs e)
{
// auto size
if (_autoSize)
{
SizeF size = e.Graphics.MeasureString(Text, Font);
if (ClientSize.Width < (int)size.Width + 1 || ClientSize.Width > (int)size.Width + 1 ||
ClientSize.Height < (int)size.Height + 1 || ClientSize.Height > (int)size.Height + 1)
{
// need resizing
ClientSize = new Size((int)size.Width + 1, (int)size.Height + 1);
return;
}
}
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.Black, Color.LightGray, LinearGradientMode.ForwardDiagonal))
e.Graphics.DrawString(Text, Font, brush, ClientRectangle);
}
}
后面的想法非常简单:如果所需的文本大小与ClientSize不同,请重写AutoSize并在Paint事件(所有内容都放在一个地方)中对其进行处理-调整大小控件(这将导致重新绘制).一件事是您必须在宽度和高度上加上+1,因为SizeF带有小数,最好是+1像素多于松散的1像素,并且文本不适合.
Idea behind is very simple: override AutoSize and process it within Paint event (everything in one place), if required size of text is different from ClientSize - resize control (which will cause redraw). One thing is what you have to add +1 to the width and height because SizeF have fractions and it's better to have +1 pixel more than loose 1 pixel sometimes and have your text not fitting.
这篇关于标签UserPaint绘制的文本不适合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!