2014-10-07 39 views
0

示例程序給你看怎麼回事:保持在另一個PictureBox的一個圖片的相對位置,同時與SizeMode.Zoom調整,的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

由於在縮放模式下圖像尺寸比率沒有改變,您可以計算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

相關問題