【问题标题】:How to drag and drop an image inside a picturebox [closed]如何在图片框中拖放图像[关闭]
【发布时间】:2020-01-15 19:06:51
【问题描述】:

我希望能够将图像拖放到图片框中,我所能找到的只是如何将图像拖放到图片框中,但在这种情况下,我有一个图片框占据了所有表单高度和宽度,背景图像是战斗垫(龙与地下城),我想要的是能够在图片框内移动图像。

我没有要显示的代码,因为我找不到执行此操作的方法。

【问题讨论】:

    标签: c# winforms draggable picturebox


    【解决方案1】:

    应该像保存原始图像、监听鼠标事件、跟踪坐标和移动裁剪一样简单。缺乏健全性检查和容错,

    private Point _origLocation;
    public Bitmap _Bitmap;
    
    private void button1_Click(object sender, EventArgs e)
    {
       // create and store the original image, the one you are going to move around
       _Bitmap = new Bitmap(@"D:\Pleiades_large.jpg");
       // set it to 0,0
       SetTemp(new Point(0, 0));
    }
    
    // on mouse down capture the X/Y position so you know where to offset
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
       => _origLocation = e.Location;
    
    // when mouse moves do something
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
       => SetTemp(new Point(_origLocation.X - e.Location.X, _origLocation.Y - e.Location.Y));
    
    private void SetTemp(Point p)
    {
    
       // if the mouse is not down, dont do anything
       if (MouseButtons != MouseButtons.Left) return;
    
       // Validate position, we cant move the image off the screen
       if (p.X < 0) p.X = 0;
       if (p.Y < 0) p.Y = 0;
       if (p.X > _Bitmap.Width - pictureBox1.Width) p.X = _Bitmap.Width - pictureBox1.Width;
       if (p.Y > _Bitmap.Height - pictureBox1.Height) p.X = _Bitmap.Height - pictureBox1.Height;
    
       // Create temp image, the size of the picture box
       var target = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    
       using (var g = Graphics.FromImage(target))
       {
          // crop the original image to the temp image
          // thats to say, where does it need to move
          g.DrawImage(
             _Bitmap, 
             new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height), 
             new Rectangle(p.X, p.Y, pictureBox1.Width, pictureBox1.Height), 
             GraphicsUnit.Pixel);
       }
    
       // Dispose and assign temp image 
       pictureBox1.Image?.Dispose();
       pictureBox1.Image = target;
    }
    

    【讨论】:

    • 你能解释一下代码吗?用最简单的方式
    • @BernardoPiedade 我已经评论了代码
    • 那么,我是否只需要复制粘贴解码代码,更改一些名称就可以了?
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 2015-12-30
    相关资源
    最近更新 更多