调整PictureBox大小时如何制作矩形 [英] How to make a rectangle move when PictureBox is resized
问题描述
我有一个PictureBox,其图片作为应用程序的背景,并设置了所有Anchors,因此可以使用该窗体调整大小。在这个PictureBox上,我创建了许多其他的东西,现在只有矩形。我在一些X和Y坐标上创建它们,这很好。添加图片以显示我正在尝试做的事情。创建的矩形实际上是小淡蓝色方块。
I have a PictureBox with a picture as a background of an application, having all the Anchors set, so it can resize with the form. On this PictureBox, I am creating many other things, for now only rectangles. I am creating them on some X and Y coordinates, that is fine. Adding a picture to show what I am trying to do. Created rectangle is actually the little light blue square.
但是,当我调整窗体的大小时,例如我最大化它,矩形停留在相同的坐标处,当然这在当时其他地方(包括仅用于保存空间的图像的一部分):我的问题是 - 如何在调整大小的过程中将矩形贴到相同的位置?注意 - 他们将不得不稍后移动,就像每隔2秒左右一样,所以它不能是绝对静态的。
But, when i resize the form, for example I maximize it, the rectangle stays at the same coordinates, which of course ar somewhere else at the moment (including only part of image to save space): My question is - how can i make the rectangle "stick" with the same place as it is, during the resize? Note - they will have to move later, like every 2 seconds or so, so it cant be absolutely static.
编辑:
这里是一些代码创建矩形
here is some of the code creating the rectangle
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更改的大小成正比。
例如:
One option could be to redraw the rectangle in new coordinates which are proportional to the PictureBox changed size. For example:
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)
这篇关于调整PictureBox大小时如何制作矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!