I have a situation in which I want to make multiple bounding boxes on a picture and want to make them editable and moveable in my winform application.
Following is my effort
public Graphics g;
public Pen pen;
public bool isMoving=false;
public int X, Y;
public int startX, startY;
public Rectangle mRect;
private void pBoxCenter_MouseDown(object sender, MouseEventArgs e)
{
isMoving = true;
// X = e.X;
//Y = e.Y;
startX= e.X;
startY = e.Y;
pBoxCenter.Cursor = Cursors.Cross;
}
private void pBoxCenter_MouseMove(object sender, MouseEventArgs e)
{
if(isMoving && X!=-1 && Y!=-1)
{
g = pBoxCenter.CreateGraphics();
pen = new Pen(Color.White, 2);
Rectangle rectangle=getRectangle(e.X, e.Y);
g.DrawRectangle(pen, rectangle);
X =e.X;
Y=e.Y;
}
}
private void pBoxCenter_MouseUp(object sender, MouseEventArgs e)
{
isMoving= false;
X = -1;
Y = -1;
}
private Rectangle getRectangle(int tempX,int tempY)
{
int X = Math.Min(startX,tempX);
int Y = Math.Min(startY,tempY);
int Width = Math.Abs(startX- tempX);
int Height = Math.Abs(startY- tempY);
mRect= new Rectangle(X,Y,Width,Height);
return mRect;
}
I am not being able to draw a single bounding box because each time I draw , multiple bounding boxes get drawn on the location.Secondly,I am not being able to draw multiple bounding boxes on different locations as code get executed once. Finally, How can I make those bounding boxes editable beacuse I might have a situation to resize those bounding boxes , moving those bounding boxes or completely deleting them .
Regards
CodePudding user response:
First it's a pity that your approach to draw the picture box is wrong, don't call CreateGraphics
, but register its Paint
event.
private void pBoxCenter_Paint(object sender, PaintEventArgs e)
{
Rectangle rectangle = getRectangle(X, Y);
e.Graphics.DrawRectangle(pen, rectangle);
}
To draw multiple bounding boxes, store multiple points and draw with a loop.
private void pBoxCenter_Paint(object sender, PaintEventArgs e)
{
foreach (Rectangle rectangle in rectangleList)
e.Graphics.DrawRectangle(pen, rectangle);
}
Use Invalidate
method at the appropriate time to refresh the picture box, so you just need modify the rectangles in the list to move or resize them. for example:
private void pBoxCenter_MouseDown(object sender, MouseEventArgs e)
{
isMoving = true;
rectangleList.Add(new Rectangle(e.X, e.Y, 0, 0));
}
private void pBoxCenter_MouseMove(object sender, MouseEventArgs e)
{
if(isMoving)
{
var lastRect = rectangleList[rectangleList.Count - 1];
rectangleList[rectangleList.Count - 1]
= new Rectangle(lastRect.X, lastRect.Y, e.X - lastRect.X, e.Y - lastRect.Y);
pBoxCenter.Invalidate();
}
}