0

我将一个包含背景图像的图片框拖到另一个图片框上,当它被放置时,我将调用一个将图像绘制到放置位置的方法。当它拖动时,它只显示一个小方形图标,表明它可以被放下。如何在被拖动的图片框中显示图像?

4

1 回答 1

1

您可以添加 2 个PictureBoxes具有相同Location, BackgroundImage, BackgroundImageLayout, Size. 1PictureBox用于拖动,1PictureBox是固定的(在运行时SizeLocation运行期间)。一切都非常简单。这是给你的演示代码:

public partial class Form1 : Form {
  public Form1(){
        InitializeComponent();
        draggingPic.Location = pictureBox2.Location;
        draggingPic.Size = pictureBox2.Size;
        draggingPic.Parent = this;          
        draggingPic.BackgroundImage = pictureBox2.BackgroundImage;
        draggingPic.BackgroundImageLayout = pictureBox2.BackgroundImageLayout;
        draggingPic.BorderStyle = pictureBox2.BorderStyle;
        draggingPic.BringToFront();//This is important, your draggingPic should be on Top
        //MouseDown event handler for draggingPic
        draggingPic.MouseDown += (s, e) => {
            downPoint = e.Location;
        };
        //MouseMove event handler for draggingPic
        draggingPic.MouseMove += (s, e) => {
            if(e.Button == MouseButtons.Left){
                draggingPic.Left += e.X - downPoint.X;
                draggingPic.Top += e.Y - downPoint.Y;
            }
        };
        //MouseUp event handler for draggingPic
        draggingPic.MouseUp += (s, e) => {                
            g.DrawImage(draggingPic.BackgroundImage, new Rectangle(pictureBox1.PointToClient(draggingPic.PointToScreen(Point.Empty)), draggingPic.Size));
            draggingPic.Location = pictureBox2.Location;
        };
        //Initialize bm 
        //your pictureBox1 should have fixed Size during runtime
        //Otherwise we have to recreate bm in a SizeChanged event handler
        bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
        pictureBox1.Image = bm;
        g = Graphics.FromImage(bm);
  }
  Bitmap bm;
  Graphics g;
  Point downPoint;
  PictureBox draggingPic = new PictureBox();
}

初步外观:

在此处输入图像描述

拖动时:

在此处输入图像描述

经过一些drag-drops

在此处输入图像描述

于 2013-09-18T04:24:46.043 回答