使用SizeMode.Zoom,Winforms调整大小时,保持图片框在另一个图片框中的相对位置

时间:2014-10-07 06:53:24

标签: c# winforms

示例程序,供您查看最新情况:

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);
        };
    }

如果您想使用我的图片:http://imgur.com/rfA0tpo,dhJX6Uc

首先我正在使用这种类型的调整大小而不是停靠,因为我的整个应用程序需要它。 无论如何,这个工作正常,现在第二个pictureBox的位置保持在你调整窗体大小的位置。问题是StretchImage模式并不是最好的,我想要使用缩放模式但是我会以某种方式需要获得图像的缩放尺寸而不是图片框以及图像在图片框上的实际偏移量。我还不知道这部分是什么,并想知道是否有人有类似的问题和解决方案。

1 个答案:

答案 0 :(得分:1)

由于在缩放模式下图像尺寸比率没有改变,因此可以在调整piturebox大小后计算图像的实际偏移量和大小。

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 = ...
}

Zoom mode