C#自定义Label 实现文字描边阴影
以下代码是在网上内容的基础上整理修改而来:
效果图:
//获取需要绘制的path
GraphicsPath GetStringPath(string s, float dpi, RectangleF rect, Font font, StringFormat format)
{
GraphicsPath path = new GraphicsPath();
//计算文字高度
float emSize = dpi * font.SizeInPoints / 72;
//向path中添加字符串及相应信息
path.AddString(s, font.FontFamily, (int)font.Style, emSize, rect, format);
return path;
}
//重写label控件的paint方法
private void l_label_Paint(object sender, PaintEventArgs e)
{
if (text == null || text.Length < 1)
return;
Graphics g = e.Graphics;//相当于画笔
Font f = font;//设置的字体
RectangleF rect = l_label.ClientRectangle;//获取控件的工作区
//计算垂直偏移量
float dy = (l_label.Height - g.MeasureString(text, font).Height) / 2.0f;
//计算水平偏移
float dx = (l_label.Width - g.MeasureString(text, font).Width) / 2.0f;
dx = 5;
//将文字显示的工作区偏移dx,dy,实现文字居中、水平居中、垂直居中
rect.Offset(dx, dy);
//文本布局信息 详细功能请查看注释 这里可有可无
StringFormat format = StringFormat.GenericTypographic;
float dpi = g.DpiY;
using (GraphicsPath path = GetStringPath(text, dpi, rect, f, format))
{
if (isShadow)
{
//阴影代码
RectangleF off = rect;
off.Offset(5, 5);//阴影偏移
using (GraphicsPath offPath = GetStringPath(text, dpi, off, f, format))
{
Brush b = new SolidBrush(Color.FromArgb(100, 0, 0, 0));//阴影颜色
g.FillPath(b, offPath);
// g.DrawPath(borderPen, offPath);//给阴影描边
b.Dispose();
}
}
g.SmoothingMode = SmoothingMode.AntiAlias;//设置字体质量
g.FillPath(fillBrush, path);//填充轮廓(填充) fillBrush 填充色
g.DrawPath(borderPen, path);//绘制轮廓(描边) borderPen 描边色
}
}
C#图形绘制记录