【发布时间】:2012-03-20 15:40:12
【问题描述】:
是否可以对标签文本应用渐变?
现在我正在接管一个控件 OnPaint 并绘制我想要的文本字符串;但是,这是具体的。我真的很想这样做,以便标签本身应用我想要的渐变颜色。因此,随着文本的变化,每个字符都将具有指定的渐变。
因此,我将应用 LinearGradientBrush,而不是使用 ForeColor。我目前正在使用 WinForms。
编辑 1
这是我目前正在使用的代码。但是,这只会将渐变应用于所有字符。我想更改它以便应用字符串中的每个字符。
// Draw the formatted text string to the DrawingContext of the control.
Font font = new Font("BankGothic Md BT", 48f, FontStyle.Bold);
LinearGradientBrush brush = new LinearGradientBrush(label1.Location, new Point(label1.Width, label1.Height), Color.Goldenrod, Color.Black);
e.Graphics.DrawString(label1.Text, font, brush, 0,0);
编辑 2
这就是我所做的。我只是扩展了 Label 类并继承了 OnPaint。
public partial class LabelEx : Label {
public LabelEx() {
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e) {
// Draw the formatted text string to the DrawingContext of the control.
//base.OnPaint(e);
Font font = new Font("Tahoma", 48f, FontStyle.Bold);
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Width, Height + 5), Color.Gold, Color.Black, LinearGradientMode.Vertical);
e.Graphics.DrawString(Text, font, brush, 0, 0);
}
}
这给了我一个很好的渐变文本标签。
谢谢!
【问题讨论】:
-
想一想,尝试将文本添加到 GraphicsPath 并用画笔绘制路径。
-
如果您使用的是框架的第 4 版,
FormattedText对象可能会对您有所帮助:msdn.microsoft.com/en-us/library/ms752098.aspx -
@SeeSharp 这似乎是 WPF 特有的。我在 WinForms 中没有 OnRender 方法。
-
@meanbunny 啊,你是对的 - 对不起,我读得太快了,错过了你说你正在使用 WinForms。对此感到抱歉。
-
请作为答案发布,而不是作为对您问题的编辑。
标签: c# winforms custom-controls paint