有没有办法为控件添加阴影?
有没有具有此功能的控件?
您必须像这样覆盖
CreateParams
属性:
private const int CS_DROPSHADOW = 0x00020000;
protected override CreateParams CreateParams
{
get
{
// add the drop shadow flag for automatically drawing
// a drop shadow around the form
CreateParams cp = base.CreateParams;
cp.ClassStyle |= CS_DROPSHADOW;
return cp;
}
}
这个问题已经存在了6年,需要一个答案。我希望任何需要这样做的人都可以从我的解决方案中推断出任何控制集的答案。我有一个面板,想要在每个子控件下方绘制阴影 - 在本例中是一个或多个面板(但该解决方案应该适用于其他控件类型,只需进行一些小的代码更改)。
由于控件的阴影必须绘制在该控件容器的表面上,因此我们首先向容器的 Paint() 事件添加一个函数。
Container.Paint += dropShadow;
dropShadow() 看起来像这样:
private void dropShadow(object sender, PaintEventArgs e)
{
Panel panel = (Panel)sender;
Color[] shadow = new Color[3];
shadow[0] = Color.FromArgb(181, 181, 181);
shadow[1] = Color.FromArgb(195, 195, 195);
shadow[2] = Color.FromArgb(211, 211, 211);
Pen pen = new Pen(shadow[0]);
using (pen)
{
foreach (Panel p in panel.Controls.OfType<Panel>())
{
Point pt = p.Location;
pt.Y += p.Height;
for (var sp = 0; sp < 3; sp++)
{
pen.Color = shadow[sp];
e.Graphics.DrawLine(pen, pt.X, pt.Y, pt.X + p.Width - 1, pt.Y);
pt.Y++;
}
}
}
}
显然,您可以从容器的集合中选择不同的控件类型,并且可以通过一些细微的调整来改变阴影的颜色和深度。
最上面的答案实际上确实产生了阴影,但我个人对它并不满意,原因有几个:
因此,由于所有这些事情,我最终为我的项目编写了自己的内容,我想我应该在这里分享它:
public partial class Form1 : Form
{
List<Control> shadowControls = new List<Control>();
Bitmap shadowBmp = null;
public Form1()
{
InitializeComponent();
shadowControls.Add(panel1);
this.Refresh();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (shadowBmp == null || shadowBmp.Size != this.Size)
{
shadowBmp?.Dispose();
shadowBmp = new Bitmap(this.Width, this.Height, PixelFormat.Format32bppArgb);
}
foreach (Control control in shadowControls)
{
using (GraphicsPath gp = new GraphicsPath())
{
gp.AddRectangle(new Rectangle(control.Location.X, control.Location.Y, control.Size.Width, control.Size.Height));
DrawShadowSmooth(gp, 100, 60, shadowBmp);
}
e.Graphics.DrawImage(shadowBmp, new Point(0, 0));
}
}
private static void DrawShadowSmooth(GraphicsPath gp, int intensity, int radius, Bitmap dest)
{
using (Graphics g = Graphics.FromImage(dest))
{
g.Clear(Color.Transparent);
g.CompositingMode = CompositingMode.SourceCopy;
double alpha = 0;
double astep = 0;
double astepstep = (double)intensity / radius / (radius / 2D);
for (int thickness = radius; thickness > 0; thickness--)
{
using (Pen p = new Pen(Color.FromArgb((int)alpha, 0, 0, 0), thickness))
{
p.LineJoin = LineJoin.Round;
g.DrawPath(p, gp);
}
alpha += astep;
astep += astepstep;
}
}
}
}
在此实现中,添加到
shadowControls
的所有控件都将涂上平滑的阴影。您应该能够对非矩形形状实现此功能,因为生成阴影的主要函数需要一个 GraphicsPath
。请注意,在将阴影绘制到表单之前,将阴影绘制到另一个位图非常重要,因为 main 函数需要 SourceCopy
的合成模式才能工作,这意味着如果您不首先将其绘制到另一个表面,则阴影后面的任何内容将被彻底取代,透明方面就没用了。我正在回答 10 年前的问题,但希望这对某人有帮助!
WPF 中有,如果您可以使用它,我不相信 Windows 窗体中有替代方案,因为 GDI+ 的功能有限。