创建如下窗口,panel1的Size为(328,246),button1中为测试代码。
1.属性Location理解
this.Location相对于屏幕的位置
panel1.Location相对于窗体的位置
labelX1.Location相对于panel1的位置
labelX3.Location相对于窗体的位置
结论:控件Location属性的值是相对于其父容器的,以父容器左上角的值为(0,0)为基准。
2.控件的工作区坐标与屏幕坐标转换
我理解为控件的工作区坐标即为Location的坐标,若转为屏幕坐标,需调用父容器控件的PointToScreen方法。若屏幕坐标转工作区坐标,调用父容器控件的PointToClient
例如:得到图中labelX1和labelX3的屏幕坐标。
Point labelX1ScreenPoint=panel1.PointToScreen(labelX1.Location);
Point labelX3ScreenPoint = this.PointToScreen(labelX3.Location);
屏幕坐标转工作区坐标
Point labelX1ClientPoint=panel1.PointToClient(labelX1ScreenPoint);
Point labelX3ClientPoint = this.PointToClient(labelX3ScreenPoint);
3.工作区矩形的大小以屏幕坐标表示
控件1.RectangleToScreen(控件2.ClientRectangle);
返回一个矩形,X、Y为控件1在屏幕坐标系中的X、Y,Size为控件2.ClientRectangle的Size。
例如:
Point labelX3ScreenPoint =this.PointToScreen(labelX3.Location);//先转化为屏幕坐标
得到labelX3ScreenPoint 的X=148,Y=356
Rectangle rectangle =labelX3.RectangleToScreen(panel1.ClientRectangle);
得到rectangle的X=148,Y=356,Width=328,Height=246
上面RectangleToScreen方法的实参为一个控件工作区的矩形,如果我们代入一个人一般的矩形,得到的矩形的X、Y是否仍为控件1在屏幕坐标系中的X、Y,结果是否定的。
例如:
Point labelX1ScreenPoint =panel1.PointToScreen(labelX1.Location);
labelX1ScreenPoint {X = 298 Y = 398}
Rectangle sourceRectangle= newRectangle(panel1.Left, panel1.Top, panel1.Width, this.panel1.Height);
sourceRectangle{X = 71 Y = 37 Width= 328 Height = 246}
Rectanglerectangle =labelX1.RectangleToScreen(sourceRectangle);
rectangle{X = 369 Y = 435 Width = 328Height = 246}从这里可以看出,得到的矩形X,Y并不为控件labelX1的屏幕坐标。原因是什么呢?
我发现“控件.ClientRectangle”得到后的矩形,其X,Y坐标都为0。而这里的sourceRectangle矩形X,Y并不为0。
总结:我理解为当调用RectangleToScreen方法时,形参使用某控件的ClientRectangle,而不要使用其它参数。(个人理解,不知道是否正确)