Home > database >  Get cursor location relative to picturebox image (not form) - C# Windows Forms .net
Get cursor location relative to picturebox image (not form) - C# Windows Forms .net

Time:11-01

I need to get the location of the cursor relative to pictureBox1, not the Windows Form itself.

My current code is returning the location relative to the form, and not pictureBox1. This is an issue as I am using that point to draw graphics on the image in the Picture box, and due to the different relative locations, it is causing the graphics to overlay at an offset depending on how much the image on the pictureBox1 is scaled, etc.

My current code for getting the cursor location and drawing (simplified to reduce lines and is all in the one forms c# code):

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    lastPoint = e.Location;
    mouseDown = true;
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    lastPoint = e.Location;
    mouseDown = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseDown == true && lastPoint != null)
    {
        using (Graphics g = Graphics.FromImage(pictureBox1.Image))
        {
            g.DrawLine(pen, lastPoint, e.Location);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        }

        pictureBox1.Invalidate();
        lastPoint = e.Location;
    }
}

Here is a demo of the issue (GIF):

img

I'd greatly appreciate some help. Thanks very much, Darcy.

CodePudding user response:

Experimented a bit with scaling the location. Following code seems to work but i still expect some problems. I presumably mixed up x,y height,width somewhere. Just push the e.Location through this everytime you need the location relative to the image .

I used Sizemode = Zoom for this.

    private Point GetScaledImageLocation(Point location)
    {
        double imgWidth = pictureBox1.Image.Width;
        double imgHeight = pictureBox1.Image.Height;
        double boxWidth = pictureBox1.Size.Width;
        double boxHeight = pictureBox1.Size.Height;

        double X = location.X;
        double Y = location.Y;
        double scale;

        if (imgWidth / imgHeight > boxWidth / boxHeight)
        {
            scale = boxWidth / imgWidth;
            double blankPart = (boxHeight - scale * imgHeight) / 2;
            Y -= blankPart;
        }
        else
        {
            scale = boxHeight / imgHeight;
            double blankPart = (boxWidth - scale * imgWidth) / 2;
            X -= blankPart;
        }

        X /= scale;
        Y /= scale;

        return new Point((int)Math.Round(X), (int)Math.Round(Y));
    }
  • Related