开发者

How to draw a rectangle in WinForm app in the correct location

I have a WinForm app that has an image displayed in a PictureBox that has the added functionality of allowing a user to draw a rectangle on the image by clicking and dragging. The Location, Height and Width of the rectangle are saved to disk.

When the image is viewed again I would like to automatically redraw that rectangle in the same position on the image.

When I redraw it, however, the Height and Width are fine but the location is always off.

The开发者_如何学C location is being captured in the MouseDown Event like so

private void pbSample_MouseDown(object Sender, MouseEventArgs e)
    {
        if (SelectMode)
          {
             StartLocation.X = e.X;
             StartLocation.Y = e.Y;
             //later on these are saved as the location of the rectangle
          }     

    }

And I am redrawing it like so

public void DrawSelectedArea(Rectangle rect)
    {
      Graphics g = this.pbSample.CreateGraphics();
      Pen p = new Pen(Brushes.Black);
      g.DrawRectangle(p, rect);
    }

Given the location from the MouseEventArgs captured during the MouseDown Event how can I calculate the correct location to redraw my rectangle?


The mouse-click points you're capturing are probably relative to the Form rather than the picture box. You either need to make sure you're capturing the coordinates properly or offset them.

Could you include a screenshot as an example?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜