我有一个带有图片作为应用程序背景的 PictureBox,设置了所有 anchor ,因此它可以随表单调整大小。在这个 PictureBox 上,我正在创建许多其他东西,目前只有矩形。我在一些 X 和 Y 坐标上创建它们,这很好。添加图片以显示我正在尝试做的事情。创建的矩形实际上是浅蓝色的小方 block 。
但是,当我调整表单大小时,例如我最大化它,矩形保持在相同的坐标,这当然是在其他地方(为了节省空间只包括图像的一部分): 我的问题是 - 在调整大小时,我怎样才能使矩形“粘在”原来的位置?注意 - 它们稍后必须移动,例如每 2 秒左右移动一次,因此它不能绝对静止。
编辑: 这是创建矩形的一些代码
private void button1_Click(object sender, EventArgs e)
{
spawn = "aircraft";
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
switch (spawn)
{
case "aircraft":
Point[] points = new Point[2];
Point bod = new Point(750, 280);
points[0] = bod;
aircraft letadlo = new aircraft(605, 180, "KLM886", 180, e.Graphics);
aircrafts[0] = letadlo;
letadlo.points = points;
break;
...
public aircraft(int x, int y, string csign, int spd, Graphics g)
{
Pen p = new Pen(Color.Turquoise, 2);
Rectangle r = new Rectangle(x, y, 5, 5);
g.DrawRectangle(p, r);
p.Dispose();
请您参考如下方法:
一种选择是在与 PictureBox 更改后的大小成比例的新坐标中重新绘制矩形。 例如:
oldX, oldY // old coordinates of the rectangle should be saved
oldPictureBoxWidth, oldPictureBoxHeight // should be saved too
//and on the PictureBox Paint event You have the new:
newPictureBoxWidth and newPictureBoxHeight
//the new coordinates of rectangle: (resize ratio is in brackets)
newX = oldX * (newPictureBoxWidth / oldPictureBoxWidth)
newY = oldY * (newPictureBoxHeight / oldPictureBoxHeight)
