C# 实现拖拉控件改变位置与大小的方法

2019-12-30 19:13:45于丽

做完这些准备工作后,将到了主要的部分,就是给控件画边框。

整个边框分为三个部分:四边框(用来设置可视区域与区域)+四条虚线(只用来显示)+八个小圆圈(用来斜角拖拉)。

所以要建立三个字段,用来分别保存这个数据。


Rectangle[] smallRects = new Rectangle[8];//边框中的八个小圆圈
Rectangle[] sideRects = new Rectangle[4];//四条边框,用来做响应区域
Point[] linePoints = new Point[5];//四条边,用于画虚线

接着就是创建用户控件的可视区域,和上面的三个变量数值。

(以下计算位置的代码,有兴趣的人可以研究下,没有的就直接Copy)  

创建边框


#region 创建边框
/// <summary>
/// 建立控件可视区域
/// </summary>
private void CreateBounds()
{
 //创建边界
 int X = baseControl.Bounds.X - square.Width - 1;
 int Y = baseControl.Bounds.Y - square.Height - 1;
 int Height = baseControl.Bounds.Height + (square.Height * 2) + 2;
 int Width = baseControl.Bounds.Width + (square.Width * 2) + 2;
 this.Bounds = new Rectangle(X, Y, Width, Height);
 this.BringToFront();
 SetRectangles();
 //设置可视区域
 this.Region = new Region(BuildFrame());
 g = this.CreateGraphics();
}
/// <summary>
/// 设置定义8个小矩形的范围
/// </summary>
void SetRectangles()
{
 //左上
 smallRects[0] = new Rectangle(new Point(0, 0), square);
 //右上
 smallRects[1] = new Rectangle(new Point(this.Width - square.Width - 1, 0), square);
 //左下
 smallRects[2] = new Rectangle(new Point(0, this.Height - square.Height - 1), square);
 //右下
 smallRects[3] = new Rectangle(new Point(this.Width - square.Width - 1, this.Height - square.Height - 1), square);
 //上中
 smallRects[4] = new Rectangle(new Point(this.Width / 2 - 1, 0), square);
 //下中
 smallRects[5] = new Rectangle(new Point(this.Width / 2 - 1, this.Height - square.Height - 1), square);
 //左中
 smallRects[6] = new Rectangle(new Point(0, this.Height / 2 - 1), square);
 //右中
 smallRects[7] = new Rectangle(new Point(square.Width + baseControl.Width + 1, this.Height / 2 - 1), square);
 //四条边线
 //左上
 linePoints[0] = new Point(square.Width / 2, square.Height / 2);
 //右上
 linePoints[1] = new Point(this.Width - square.Width / 2 - 1, square.Height / 2);
 //右下
 linePoints[2] = new Point(this.Width - square.Width / 2 - 1, this.Height - square.Height / 2);
 //左下
 linePoints[3] = new Point(square.Width / 2, this.Height - square.Height / 2 - 1);
 //左上
 linePoints[4] = new Point(square.Width / 2, square.Height / 2);
 //整个包括周围边框的范围
 ControlRect = new Rectangle(new Point(0, 0), this.Bounds.Size);
}
/// <summary>
/// 设置边框控件可视区域
/// </summary>
/// <returns></returns>
private GraphicsPath BuildFrame()
{
 GraphicsPath path = new GraphicsPath();
 //上边框
 sideRects[0] = new Rectangle(0, 0, this.Width - square.Width - 1, square.Height + 1);
 //左边框
 sideRects[1] = new Rectangle(0, square.Height + 1, square.Width + 1, this.Height - square.Height - 1);
 //下边框
 sideRects[2] = new Rectangle(square.Width + 1, this.Height - square.Height - 1, this.Width - square.Width - 1, square.Height + 1);
 //右边框
 sideRects[3] = new Rectangle(this.Width - square.Width - 1, 0, square.Width + 1, this.Height - square.Height - 1);
 path.AddRectangle(sideRects[0]);
 path.AddRectangle(sideRects[1]);
 path.AddRectangle(sideRects[2]);
 path.AddRectangle(sideRects[3]);
 return path;
}
#endregion