这是一段可以帮助您入门的代码。
drawShadow 方法沿GraphicsPath 绘制具有给定颜色和深度的阴影。
使用GraphicsPath 可以让您绘制比Rectangles 更复杂形状的阴影。
阴影是用一个颜色矢量绘制的,该矢量逐渐从阴影到背景颜色并向右和向下移动。 (可以通过改变阴影向量来改变方向。值大于1需要更大的Pen宽度!(*))
为了演示例程,我添加了一个getRectPath 函数,该函数从Rectangle 创建一个GraphicsPath 和一个调用绘图例程的按钮单击。
当然,在生产代码中,您必须将其附加到 Paint 事件!
void drawShadow(Graphics G, Color c, GraphicsPath GP, int d)
{
Color[] colors = getColorVector(c, this.BackColor, d).ToArray();
for (int i = 0; i < d; i++)
{
G.TranslateTransform(1f, 0.75f); // <== shadow vector!
using (Pen pen = new Pen(colors[i], 1.75f ) ) // <== pen width (*)
G.DrawPath(pen, GP);
}
G.ResetTransform();
}
List<Color> getColorVector(Color fc, Color bc, int depth)
{
List<Color> cv = new List<Color>();
float dRed = 1f * (bc.R - fc.R) / depth;
float dGreen = 1f * (bc.G - fc.G) / depth;
float dBlue = 1f * (bc.B - fc.B) / depth;
for (int d = 1; d <= depth; d++)
cv.Add(Color.FromArgb(255, (int) (fc.R + dRed * d),
(int) (fc.G + dGreen * d), (int) (fc.B + dBlue * d) ));
return cv;
}
GraphicsPath getRectPath(Rectangle R)
{
byte[] fm = new byte[3];
for (int b = 0; b < 3; b++) fm[b] = 1;
List<Point> points = new List<Point>();
points.Add(new Point(R.Left, R.Bottom));
points.Add(new Point(R.Right, R.Bottom));
points.Add(new Point(R.Right, R.Top));
return new GraphicsPath(points.ToArray(), fm);
}
private void button1_Click(object sender, EventArgs e)
{
using (Graphics G = this.CreateGraphics())
drawShadow(G, Color.Black, getRectPath(new Rectangle(111, 111, 222, 222)), 17);
}
编辑:我已经更改了解决方案,以允许复杂的阴影和任意阴影矢量,而不会出现 Alpha 通道的重叠造成难看的伪影。这假设背景具有统一的颜色!