我正在尝试编写一个程序,允许用户将图像拖放到程序中,然后能够选择图像,移动图像,重新调整大小,裁剪图像等.
到目前为止,我已经创建了一个由面板组成的窗体.用户可以将图片文件拖到面板上,并且当鼠标被丢弃并且图片被加载到图片框中时,将在鼠标坐标处创建图片框.我可以用这种方式添加几个图像.
现在我想让用户操作并移动他们放入面板的图像.
我试过寻找解决方案,但似乎无法找到我理解的答案.
任何帮助深表感谢..
这是我目前的代码
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); } }
解决方法
您可以在用户最初单击时获取鼠标位置,然后在PictureBox的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...