public static void SetTextShadow(this Graphics e, Font font, Size size, Padding padding, string txt, int depth, Color shadowColor, Color faceColor, bool connect)
{
SizeF txtSize = txt.MeasureString(font);
PointF txtPointF = new PointF((size.Width - padding.Left - txtSize.Width) / 2, (size.Height - padding.Top - txtSize.Height) / 2);
e.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
using SolidBrush solidBrush = new SolidBrush(shadowColor);
e.DrawString(txt, font, solidBrush, new PointF(txtPointF.X + depth, txtPointF.Y + depth));
if (connect)
{
for (int i = depth - 1; i > 0; i--)
{
solidBrush.Color = ControlPaint.Light(shadowColor, i / (float)depth);
e.DrawString(txt, font, solidBrush, new PointF(txtPointF.X + i, txtPointF.Y + i));
}
}
solidBrush.Color = faceColor;
e.DrawString(txt, font, solidBrush, txtPointF);
}
}
上面代码中,depth为投射深度,shadowColor为阴影颜色,faceColor为字体颜色,connect用于模拟体居光效果。
/// <summary>
/// 文本阴影
/// </summary>
public class TextShadow : Control
{
public TextShadow()
{
}
private Color _shadowColor = Color.Gray;
public Color ShadowColor
{
get => _shadowColor;
set
{
_shadowColor = value;
this.Invalidate();
}
}
private int _depth = 2;
public int Depth
{
get => _depth;
set
{
_depth = value;
this.Invalidate();
}
}
private bool _connect = true;
public bool Connect
{
get => _connect;
set
{
_connect = value;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SetTextShadow(this.Font, this.Size, this.Padding, this.Text, this._depth, this._shadowColor, this.ForeColor, this._connect);
}
}
在窗体中拖入此控件,效果如下:
其它扩展
internal static class SystemEx
{
/// <summary>
/// 计算文字大小
/// </summary>
/// <param name="text">文字</param>
/// <param name="font">字体</param>
/// <returns>大小</returns>
public static SizeF MeasureString(this string text, Font font)
{
return Graphics().MeasureString(text, font);
}
private static Graphics TempGraphics;
/// <summary>
/// 提供一个Graphics,常用于需要计算文字大小时
/// </summary>
/// <returns>大小</returns>
public static Graphics Graphics()
{
if (TempGraphics == null)
{
Bitmap bmp = new Bitmap(1, 1);
TempGraphics = bmp.Graphics();
}
return TempGraphics;
}
/// <summary>
/// 图片的绘图图元
/// </summary>
/// <param name="image">图片</param>
/// <returns>绘图图元</returns>
public static Graphics Graphics(this Image image)
{
return System.Drawing.Graphics.FromImage(image);
}
}