Reputation: 1132
Sample program for you to see whats going on:
private void Form1_Load(object sender, EventArgs e)
{
int x = 0;
int y = 0;
this.Size = new Size(600, 600);
PictureBox pb = new PictureBox();
//use whatever somewhat bigger img
pb.Image = Image.FromFile(@"");
pb.Location = new Point(5, 5);
pb.Size = new Size(500, 500);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(pb);
PictureBox test30x30 = new PictureBox();
//use a 30x30 img
test30x30.Image = Image.FromFile(@"");
test30x30.Size = new Size(30, 30);
test30x30.BackColor = Color.Transparent;
pb.Controls.Add(test30x30);
pb.MouseClick += (ss, ee) =>
{
test30x30.Location = new Point(ee.X - test30x30.Image.Width / 2, ee.Y - test30x30.Image.Height);
x = (int)(((double)test30x30.Location.X + test30x30.Image.Width/2) / (double)pb.Width * 1024);
y = (int)(((double)test30x30.Location.Y + test30x30.Image.Height) / (double)pb.Height * 1024);
};
this.Resize += (ss, ee) =>
{
pb.Size = new Size(this.Width - 100, this.Height - 100);
test30x30.Location = new Point((int)((double)x / 1024 * (double)pb .Width) - test30x30.Image.Width / 2, (int)((double)y / 1024 * ( double)pb.Height) - test30x30.Image.Height);
};
}
If you want to use my images: https://i.sstatic.net/w8OKn.png
First off i am using this type of resizing and not docking because my whole application requires it. Anyways, this works fine for now the position of the second pictureBox stays where it should be if you resize the form. The problem is that StretchImage mode isnt really the best and i would want to use Zoom mode but then i would somehow need to get the zoomed size of the imageand not the picturebox and the actual offset of where the image is on the picturebox. I wasnt able to figure this part out yet and was wondering if anybody had a similiar problem and solution.
Upvotes: 0
Views: 624
Reputation: 12993
Since in Zoom mode the image size ratio is not changed, you can calculate the actual offset and size of image after piturebox is resized.
double imgWidth = 0.0;
double imgHeight = 0.0;
double imgOffsetX = 0.0;
double imgOffsetY = 0.0;
double dRatio = pb.Image.Height / (double)pb.Image.Width; //dRatio will not change during resizing
pb.MouseClick += (ss, ee) =>
{
test30x30.Location = new Point(ee.X - test30x30.Image.Width / 2, ee.Y - test30x30.Image.Height);
//x = ...
//y = ...
};
this.Resize += (ss, ee) =>
{
pb.Size = new Size(this.ClientSize.Width - 100, this.ClientSize.Height - 100);
};
pb.SizeChanged += (ss, ee) =>
{
//recalculate image size and offset
if (pb.Height / pb.Width > dRatio) //case 1
{
imgWidth = pb.Width;
imgHeight = pb.Width * dRatio;
imgOffsetX = 0.0;
imgOffsetY = (pb.Height - imgHeight) / 2;
}
else //case 2
{
imgHeight = pb.Height;
imgWidth = pb.Height / dRatio;
imgOffsetY = 0.0;
imgOffsetX = (pb.Width - imgWidth) / 2;
}
//test30x30.Location = ...
}
Upvotes: 1