一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net C#中 PictureBox控件拖动与图片拖动代码

时间:2022-06-25 08:21:59 编辑:袖梨 来源:一聚教程网

 

思路是这样的.得有三个变量.
记录x坐标: int xPos;
记录y坐标: int yPos;
记录是否按下鼠标: bool MoveFlag;

 代码如下 复制代码

//在picturebox的鼠标按下事件里,记录三个变量.
private void picBox_MouseDown(object sender, MouseEventArgs e)
{
    MoveFlag = true;//已经按下.
    xPos = e.X;//当前x坐标.
    yPos = e.Y;//当前y坐标.
}

//在picturebox的鼠标按下事件里.
private void picBox_MouseUp(object sender, MouseEventArgs e)
{
    MoveFlag = false;
}

//在picturebox鼠标移动
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (MoveFlag)
    {
        picBox.Left += Convert.ToInt16(e.X - xPos);//设置x坐标.
        picBox.Top += Convert.ToInt16(e.Y - yPos);//设置y坐标.
    }
}

这样就可以实现控件在容器里的移动


在pictureBox中拖动图片的实现代码     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 bm = new Bitmap(this.pictureBox1.Image);

                Graphics g = pictureBox1.CreateGraphics();
                g.Clear(pictureBox1.BackColor);
                g.DrawImage(bm, mx, my);

                p.X = e.X;
                p.Y = e.Y;

                bm.Dispose();
                g.Dispose();
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            pictureBox1.Cursor = Cursors.Default; //松开鼠标时,形状恢复为箭头
            wselected = false;
        }

热门栏目