GDI+ 中的模糊阴影






4.53/5 (32投票s)
为 GDI+ 绘制的对象创建模糊阴影。
引言
我为公司开发一个流程图软件,并且一直在寻找美化应用的方法。在完成应用程序的核心功能后,我开始关注用户会注意到或使用的细节,并觉得“哇,真不错”。因此,在流程图对象的外观方面,我希望添加一个阴影,以显示绘图画布的深度。我搜索了网络,发现所有方法都是使用图像并对其进行倾斜或拉伸,然后将其绘制在对象下方以产生阴影。所以我开始使用透明颜色绘制对象的阴影,但问题出现了。效果还可以,但边缘太锐利了,这时我才想到了这个解决方案。希望你喜欢并使用它 - Larry
概述
在这里,我将向你展示一种我找到的方法,用于为 GDI+ 绘制的形状创建具有模糊边缘的阴影。首先,我们需要设置阴影应该从形状绘制的距离。在这个例子中,我使用一个 NumericUpDown
控件,以便我们可以更改此距离并查看哪个距离看起来最好。
// set the shadow distance
// since we are going back and up minus the value from zero
// this will put the shadow down and to the right of the Shape
_ShadowDistance = 0f - (float)nmDistance.Value;
// force a redraw of the canvas
picCanvas.Invalidate();
现在我们已经设置了距离,让我们开始绘制。在这里,我不会赘述如何绘制对象,只讲解阴影的绘制。所以到目前为止,我们已经创建了一个 GraphicsPath()
来绘制我们的圆角矩形。现在,我们需要创建阴影,方法如下。
// this is where we create the shadow effect, so we will use a
// pathgradientbursh and assign our GraphicsPath that we created of a
// Rounded Rectangle
using(PathGradientBrush _Brush = new PathGradientBrush(_Path))
{
// set the wrapmode so that the colors will layer themselves
// from the outer edge in
_Brush.WrapMode = WrapMode.Clamp;
// Create a color blend to manage our colors and positions and
// since we need 3 colors set the default length to 3
ColorBlend _ColorBlend = new ColorBlend(3);
// here is the important part of the shadow making process, remember
// the clamp mode on the colorblend object layers the colors from
// the outside to the center so we want our transparent color first
// followed by the actual shadow color. Set the shadow color to a
// slightly transparent DimGray, I find that it works best.|
_ColorBlend.Colors = new Color[]{Color.Transparent,
Color.FromArgb(180, Color.DimGray),
Color.FromArgb(180, Color.DimGray)};
// our color blend will control the distance of each color layer
// we want to set our transparent color to 0 indicating that the
// transparent color should be the outer most color drawn, then
// our Dimgray color at about 10% of the distance from the edge
_ColorBlend.Positions = new float[]{0f, .1f, 1f};
// assign the color blend to the pathgradientbrush
_Brush.InterpolationColors = _ColorBlend;
// fill the shadow with our pathgradientbrush
e.Graphics.FillPath(_Brush, _Path);
}
这样做非常简单,但比仅仅使用略微透明的画笔绘制阴影,能提供更好的呈现效果。我希望这对某人有所帮助。