winform重绘控件边框

首先添加一个用户控件

 对于重绘边框有三个需要考虑的东西

1:是否显示边框

2:边框颜色

3:边框宽度

所以定义三个私有变量

/// <summary>
/// 是否显示边框
/// </summary>
private bool _isShowRect = false;
/// <summary>
/// 边框颜色
/// </summary>
private Color _rectColor = Color.FromArgb(220, 220, 220);
/// <summary>
/// 边框宽度
/// </summary>
private float _rectWidth = 2;

使用OnPaint事件可以随时绘制图形所以我们需要重写OnPaint事件


protected override void OnPaint(PaintEventArgs e)
{
GraphicsPath graphicsPath = new GraphicsPath();
/////绘制边框
//graphicsPath.AddLine(new Point(0, 0), new Point(base.Width,0));
//graphicsPath.AddLine(new Point(0, 0), new Point(0,base.Height));
////-1的问题是微软控件像素的问题,所以不直接用下面获取控件的方式
//graphicsPath.AddLine(new Point(0, base.Height-1), new Point(base.Width-1, base.Height-1));
//graphicsPath.AddLine(new Point( base.Width-1, base.Height), new Point(base.Width-1,0));
///或者下面-1的方法
Rectangle clientRectangle = base.ClientRectangle;
clientRectangle.Width -= 1;
clientRectangle.Height -= 1;
graphicsPath.AddRectangle(clientRectangle);
if (IsShowRect)
{
Color rectColor = this._rectColor;
Pen pen = new Pen(rectColor,_rectWidth);
e.Graphics.DrawPath(pen, graphicsPath);
}
//调用基类方法
//OnPaint方法引发Paint事件,所以重写OnPaint方法,一定要调用base.OnPaint,否则就不会引发Paint事件了。
base.OnPaint(e);//调用基类方法
}

为什么要-1 画个图给大家就明白了

 

猜你喜欢

转载自www.cnblogs.com/qpjlove/p/12378175.html
今日推荐