我正在将带有背景图像的图片框拖到另一个图片框上,当它被删除时,我将调用一个方法将图像绘制到放置位置。当它拖动时,它只显示小方块图标,表示它可以被删除。如何在拖动的图片框中显示图像?
答案 0 :(得分:1)
您可以添加具有相同PictureBoxes
的2 Location, BackgroundImage, BackgroundImageLayout, Size
。 1 PictureBox
用于拖动,1 PictureBox
已修复(在Size
和Location
运行时)。一切都很简单。以下是您的演示代码:
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
: