用C#如何实现在picturebox里拖动图片的功能?大神们帮帮忙

 我来答
转淘您2240
推荐于2016-10-23 · 超过64用户采纳过TA的回答
知道答主
回答量:131
采纳率:66%
帮助的人:59.8万
展开全部
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { 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) { } 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);//填充矩形 } private void pictureBox1_Click(object sender, EventArgs e) { } bool wselected = false; Point p = new Point(); private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { pictureBox1.Cursor = Cursors.Hand; //按下鼠标时,将鼠标形状改为手型 wselected = true; p.X = e.X; p.Y = e.Y; } 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_MouseUp(object sender, MouseEventArgs e) { pictureBox1.Cursor = Cursors.Default; //松开鼠标时,形状恢复为箭头 wselected = false ; this.pictureBox1.Cursor = Cursors.Default; } } }
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式