日期:2014-05-18  浏览次数:21271 次

用mouseclick事件在picturebox获取的坐标不准确??
我用
C# code
//MessageBox.Show(e.X.ToString(), e.Y.ToString());//显示X坐标
获取坐标值,然后在picturebox上画矩形,为什么矩形画的位置偏差好大?求大神指导,谢谢了。
C# code
         if (e.X > 330 && e.X < 360 && e.Y > 140 && e.Y < 165)
            {
                Graphics g = Graphics.FromImage(pictureBox1.Image);
                Pen mpen = new Pen(Color.Red, 4);
                g.DrawRectangle(mpen,330, 140, 50, 50);
                this.pictureBox1.Refresh();
            }


其中(330,140)和(360,165)是对应点击的鼠标值.

------解决方案--------------------
不是,你画的相对于picturebox的坐标,由于图片和picturebox不一般大,画到图片上看起来就是缩小或者放大了,你只要将坐标改到和图片一致就可以了,我把代码给你
C# code

      /// <summary>
        /// 坐标缩放,返回符合图片大小的坐标
        /// </summary>
        /// <param name="r">画图框坐标</param>
        /// <param name="x">画板宽</param>
        /// <param name="y">画板高</param>
        /// <param name="width">图片实际宽</param>
        /// <param name="height">图片实际高</param>
        /// <returns></returns>
        private Rectangle ResizeRect(Rectangle r)
        {
            int Left = r.Left * frmBackGround.BackgroundImage.Width / frmBackGround.Width;
            int Top = r.Top * frmBackGround.BackgroundImage.Height / frmBackGround.Height;
            int Width = r.Width * frmBackGround.BackgroundImage.Width / frmBackGround.Width;
            int Height = r.Height * frmBackGround.BackgroundImage.Height / frmBackGround.Height;
            r = new Rectangle(Left, Top, Width, Height);
            return r;

        }

------解决方案--------------------
矩形要保留的图片上么,如果只是给用户看,那可以这样
注册 pictureBox1 Paint 事件
C# code
private bool drawRect = false;

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (drawRect)
    {
        Pen mpen = new Pen(Color.Red, 4);
        e.Graphics.DrawRectangle(mpen, 330, 140, 50, 50);
    }
}

private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.X > 330 && e.X < 360 && e.Y > 140 && e.Y < 165)
    {
        drawRect = true;
        this.pictureBox1.Invalidate();
    }
}