简体   繁体   English

在Windows窗体中操作拖放图像c#

[英]Manipulating drag and drop images in windows forms c#

I am trying to write a program which will allow a user to drag and drop images into the program and then be able to select the image, move it about, re-size it, crop it etc. 我正在尝试编写一个程序,允许用户将图像拖放到程序中,然后能够选择图像,移动图像,重新调整大小,裁剪图像等。

So far I have created a windows form which consists of a panel. 到目前为止,我已经创建了一个由面板组成的窗体。 A user can drag a picture file onto the panel and a picturebox will be created at the coordinates of the mouse when it is dropped and an image is loaded in the picturebox. 用户可以将图片文件拖到面板上,并且当鼠标被丢弃并且图片被加载到图片框中时,将在鼠标坐标处创建图片框。 I can add several images in this fashion. 我可以用这种方式添加几个图像。

Now I want to allow the user to manipulate and move about the images that they have dropped into the panel. 现在我想让用户操作并移动他们放入面板的图像。

I have tried searching for solutions but cant seem to find an answer which I understand. 我试过寻找解决方案,但似乎无法找到我理解的答案。

Any help is much appreciated.. 任何帮助深表感谢..

This is my current code 这是我目前的代码

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

    }

You can get the mouse position when the user initially clicks and then track the mouse position in the PictureBox's MouseMove event. 您可以在用户最初单击时获取鼠标位置,然后在PictureBox的MouseMove事件中跟踪鼠标位置。 You can attach these handlers to multiple PictureBoxes. 您可以将这些处理程序附加到多个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);
        }
    }
}

For dynamic PictureBoxes you can attach the handlers like this 对于动态PictureBoxes,您可以像这样附加处理程序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM