曾经在学习WPF的情况下,用过一个编写XAML的小工具Kaxaml,觉得这个小工具的关闭按钮挺不错的,如下图所示:
为了练习GDI+,用代码实现了这个效果。虽然可能不是100%很像,但是从学习的角度来数,我觉得还算满意了。
代码如下:
首先需要绘制一个关闭按钮,代码如下:
///
/// 关闭按钮
///
///
private void CloseButton(Graphics g)
{
//Point组 绘制关闭按钮的两个叉
Point[] points = new Point[4];
///
points[0] = new Point(rect.X, rect.Y);
points[1] = new Point(rect.Bottom, rect.Right);
g.DrawLine(new Pen(new SolidBrush(ColorTable.CloseLineColor), 2.0f), points[0], points[1]);
// /
points[2] = new Point(rect.Right, rect.X);
points[3] = new Point(rect.X, rect.Bottom);
g.DrawLine(new Pen(new SolidBrush(ColorTable.CloseLineColor), 2.0f), points[2], points[3]);
}
用专门的一个方法来绘制底纹的圆形图案:
///
/// 底纹圆
///
///
private void BottomClicle(Graphics g)
{
//绘制最底层的圆
using (LinearGradientBrush linearBrush = new LinearGradientBrush(
rect,
ColorTable.BottomCircleTopColor,
ColorTable.BottomCircleBottmColor,
LinearGradientMode.Vertical))
{
g.FillEllipse(linearBrush, rect);
}
rect.Inflate(CircleSpace, CircleSpace);
//绘制中间层的矩形
SolidBrush solidBrush = new SolidBrush(ColorTable.MiddleCircleColor);
g.FillEllipse(solidBrush, rect);
}
相应Paint事件:
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
//指定绘制矩形的大小
rect = ClientRectangle;
rect.Inflate(CircleSpace, CircleSpace);
BottomClicle(g);
//缩小4个像素 确定最上层的关闭按钮的区域
rect.Inflate(CloseSpace + CircleSpace, CloseSpace + CircleSpace);
CloseButton(g);
MouseLeave事件:
private void CloseButtonEx_MouseLeave(object sender, EventArgs e)
{
Invalidate();//强制刷新
}
另外几个鼠标事件:
private void CloseButtonEx_MouseDown(object sender, MouseEventArgs e)
{
rect = ClientRectangle;
rect.Inflate(-6, -6);
Graphics g = this.CreateGraphics();
g.SmoothingMode = SmoothingMode.HighQuality;
Color hoverColor = ColorTable.CloseHover;
SolidBrush solidBrush = new SolidBrush(hoverColor);
g.FillEllipse(solidBrush, rect);
rect = ClientRectangle;
rect.Inflate(-10, -10);
Point loca = rect.Location;
rect.Location = new Point(loca.X + 1, loca.Y + 1);
CloseButton(g);
}
private void CloseButtonEx_MouseUp(object sender, MouseEventArgs e)
{
Invalidate();
}
private void CloseButtonEx_MouseHover(object sender, EventArgs e)
{
rect = ClientRectangle;
rect.Inflate(-6, -6);
Graphics g = this.CreateGraphics();
g.SmoothingMode = SmoothingMode.HighQuality;
Color hoverColor = ColorTable.CloseHover;
SolidBrush solidBrush = new SolidBrush(hoverColor);
g.FillEllipse(solidBrush, rect);
Update();
}
至此,一个关闭按钮控件实现了。