2013-07-05 31 views
4

我正在尝试编写一个程序,该程序允许用户将图像拖放到程序中,然后可以选择图像,移动图像,重新调整大小,裁剪等。在Windows窗体中操纵拖放图像c#

到目前为止,我创建了一个窗体,它由一个面板组成。用户可以将图片文件拖动到面板上,当鼠标被拖放并将图片加载到图片框时,将在鼠标的坐标处创建图片框。我可以用这种方式添加几个图像。

现在我想允许用户操纵和移动他们已经放入面板的图像。

我尝试过寻找解决方案,但似乎找不到我明白的答案。

任何帮助深表感谢..

这是我当前的代码

private void panel1_DragEnter(object sender, DragEventArgs e) 
    { 
     e.Effect = DragDropEffects.All; 
    } 



    private void panel1_DragDrop(object sender, DragEventArgs e) 
    { 
     String[] imagePaths = (String[])e.Data.GetData(DataFormats.FileDrop); 
     foreach (string path in imagePaths) 
     { 
      Point point = panel1.PointToClient(Cursor.Position); 

      PictureBox pb = new PictureBox(); 
      pb.ImageLocation = path; 
      pb.Left = point.X; 
      pb.Top = point.Y; 

      panel1.Controls.Add(pb); 

      //g.DrawImage(Image.FromFile(path), point); 
     } 

    } 

回答

1

你可以得到鼠标的位置,当用户开始点击,然后跟踪在图片框的MouseMove事件鼠标的位置。您可以将这些处理程序附加到多个PictureBox。

private int xPos; 
private int yPos; 

private void pb_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     xPos = e.X; 
     yPos = e.Y; 
    } 
} 

private void pb_MouseMove(object sender, MouseEventArgs e) 
{ 
    PictureBox p = sender as PictureBox; 

    if(p != null) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      p.Top += (e.Y - yPos); 
      p.Left += (e.X - xPos); 
     } 
    } 
} 

对于动态PictureBoxes您可以将处理程序这样

PictureBox dpb = new PictureBox(); 
dpb.MouseDown += pb_MouseDown; 
dbp.MouseMove += pb_MouseMove; 
//fill the rest of the properties... 
+0

感谢您的答复! – kev3kev3

+0

如果在程序运行时生成picturebox,那么我如何将这些处理程序附加到picturebox? – kev3kev3

+0

我已经更新了答案。 – keyboardP