有没有办法为控件添加阴影效果?
是否有带有此功能的控件可用?
有没有办法为控件添加阴影效果?
是否有带有此功能的控件可用?
你需要像这样覆盖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;
}
}
SetStyle(ControlStyles.DoubleBuffer, true); UpdateStyles();
- Simon LinderContainer.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
。请注意,在将阴影绘制到表单之前,重要的是你先将其绘制到另一个位图上,因为主要函数需要使用SourceCopy
合成模式才能正常工作,这意味着如果你不先将其绘制到另一个表面上,阴影后面的任何内容都将被完全替换,透明度方面就没有用处了。我正在回答一个十年前的问题,但希望这对某些人有所帮助!alpha
不会是0
吗?alpha
从零开始,并且只在循环中的绘图后进行更改,然后添加astep
,但在第一个循环中,astep
也是零。 - undefined如果您能够使用WPF,那么在WPF中有这个功能。但是,由于GDI+的能力有限,我认为在Windows Forms中没有替代方案。
这样可以通过调整外部列和行的大小来灵活调整大小。这是一个快速草图,以可视化设计师中表格布局的外观:
应用程序中最终结果的实际截图: