The following method is part of a winform label inherited class. The goal is to make a halo or glow effect on text. So far the effect is actually an outline. Its worth keeping as its not bad but its not there yet.
protected override void OnPaint(PaintEventArgs e)
{
if (this.Text.Length == 0) return;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
Rectangle rc = new Rectangle(ClientRectangle.X + Padding.Left,
ClientRectangle.Y + Padding.Top,
ClientRectangle.Width - (Padding.Left + Padding.Right),
ClientRectangle.Height - (Padding.Top + Padding.Bottom));
StringFormat fmt = new StringFormat(StringFormat.GenericTypographic)
{
Alignment = TextAlign == ContentAlignment.TopLeft || TextAlign == ContentAlignment.MiddleLeft || TextAlign == ContentAlignment.BottomLeft
? StringAlignment.Near
: TextAlign == ContentAlignment.TopCenter || TextAlign == ContentAlignment.MiddleCenter || TextAlign == ContentAlignment.BottomCenter
? StringAlignment.Center
: StringAlignment.Far
};
if ((haloSize < 1) | (haloColor == Color.Transparent))
{
using (var brush = new SolidBrush(this.ForeColor))
{
e.Graphics.DrawString(Text, Font, brush, rc, fmt);
}
}
else
{
using (var path = new GraphicsPath())
using (var halopen = new Pen(new SolidBrush(this.haloColor), haloSize) { LineJoin = LineJoin.Round })
using (var brush = new SolidBrush(ForeColor))
{
if (fmt.Alignment == StringAlignment.Center) rc.X += rc.Width / 2;
if (fmt.Alignment == StringAlignment.Far) rc.X += rc.Width;
path.AddString(Text, Font.FontFamily, (int)Font.Style, rc.Height, rc.Location, fmt);
//path.AddString(Text, Font.FontFamily, (int)Font.Style, rc.Height, rc, fmt);
e.Graphics.DrawPath(halopen, path);
e.Graphics.FillPath(brush, path);
}
}
}
Two questions.
- Why does the line that is commented out using
AddString
with aRectangle
not work but it does work with aPoint
? - The halo glow effect can be done with progressively smaller brush size and color change but that feels like inventing a new wheel. Is there an easy way to do this or an open source library with this already?