首先添加一個用戶控件
對於重繪邊框有三個需要考慮的東西
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 畫個圖給大家就明白了