I'm dynamically adding Labels to panels in my code.
Something I want to do is be able to outline the font so that it can stand out from the background color of the panel.
The problem is I don't know how to create a outline for my font or even a shadow effect in C# using Winforms.
Anyone know what I should look at or can point me in the right direction? If you don't understand what I mean, the following picture is what I would like: (the Outer lining)
I think you have to custom paint your own control. Here is an example for a Label
. Note that it's just a demo, you should try finding out more on custom painting in winforms:
public class CustomLabel : Label
{
public CustomLabel()
{
OutlineForeColor = Color.Green;
OutlineWidth = 2;
}
public Color OutlineForeColor { get; set; }
public float OutlineWidth { get; set; }
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
using (GraphicsPath gp = new GraphicsPath())
using (Pen outline = new Pen(OutlineForeColor, OutlineWidth)
{ LineJoin = LineJoin.Round})
using(StringFormat sf = new StringFormat())
using(Brush foreBrush = new SolidBrush(ForeColor))
{
gp.AddString(Text, Font.FontFamily, (int)Font.Style,
Font.Size, ClientRectangle, sf);
e.Graphics.ScaleTransform(1.3f, 1.35f);
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.DrawPath(outline, gp);
e.Graphics.FillPath(foreBrush, gp);
}
}
}
You can change the outline color via OutlineForeColor
property, you can change the outline width via the OutlineWidth
property. When you change these properties in the designer, the effect is not applied immediately (because there is not any code to do that, I want to keep it short and simple), the effect is applied only when the form is focused.
What you can add more is mapping the TextAlign
to the Alignment
of the StringFormat
(named sf
in the code), you can also override some event raising methods to add more control over the look and feel (such as to change the ForeColor
when the mouse is over the label...). You can even create some shadow effect and glow effect (it requires a little much more code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With