C#中picturebox控件如何对图像进行拖拽
1个回答
展开全部
下面这个代码可以实现,本人已经测试过:public partial class Form1 : Form { public Form1() { InitializeComponent(); foreach (Control c in this.Controls) { if (c is PictureBox) { c.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove); c.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown); } } } private void Form1_Load(object sender, EventArgs e) { this.pictureBox1.Image = Image.FromFile(@"E:\Images\test.jpg"); } int driftX = 0, driftY = 0; int mx = 0, my = 0; private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (wselected) { driftX = p.X - e.X; driftY = p.Y - e.Y; mx = mx - driftX; my = my - driftY; Bitmap JPEG = new Bitmap(this.pictureBox1.Image); Graphics g = pictureBox1.CreateGraphics(); g.Clear(pictureBox1.BackColor); g.DrawImage(JPEG, mx, my); p.X = e.X; p.Y = e.Y; JPEG.Dispose(); g.Dispose();//图像移动的距离 } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { pictureBox1.Cursor = Cursors.Hand; //按下鼠标时,将鼠标形状改为手型 wselected = true; p.X = e.X; p.Y = e.Y; } private void button1_Click(object sender, EventArgs e) { Graphics g = this.CreateGraphics();//生成图形对象 SolidBrush BlueBrush = new SolidBrush(Color.Blue);//生成填充用的画刷 int x = 15;//定义外接矩形的左上角坐标和高度及宽度 int y = 15; int width = 200; int height = 100; Rectangle rect = new Rectangle(x, y, width, height);//定义矩形 g.FillRectangle(BlueBrush, rect);//填充矩形 } bool wselected = false; Point p = new Point(); private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { pictureBox1.Cursor = Cursors.Default; //松开鼠标时,形状恢复为箭头 wselected = false; this.pictureBox1.Cursor = Cursors.Default; } }Caillen
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询