Reputation: 2857
I want to draw Square on Image not the rectangle when I perform mouse move operation to Top, Left, Bottom, Right direction its Height and Width will be increase in same length.
below is my code it does not display square I want exact code for Square
public Form1()
{
InitializeComponent();
}
Rectangle currRect;
Point endPoint;
bool isDrag;
Point startPoint;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
startPoint = new Point(e.X, e.Y); //
if (e.Button == MouseButtons.Left)
{
currRect = new Rectangle();
currRect.X = startPoint.X;
currRect.Y = startPoint.Y;
isDrag = true;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
endPoint = new Point(e.X, e.Y);
currRect.Width = endPoint.X - startPoint.X;
currRect.Height = endPoint.Y - startPoint.Y;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
isDrag = false;
Graphics graphics = this.pictureBox1.CreateGraphics();
graphics.DrawRectangle(new Pen(Brushes.Red), currRect.X, currRect.Y, currRect.Width, currRect.Height);
}
also one thing when I going to increase the size of square its starting point or we can say that its Top,Left co-ord remains steady or constant when I am increasing in Top, Left, Bottom, Right direction.
this starting point is not steady when I move the mouse cursor its starting point gets change i don't want this so please help me to figure out from this situation
Upvotes: 2
Views: 1784
Reputation: 6317
Your code is drawing a rectangle, not a square. If you want to draw a square, you need to make the width and height identical.
If you modify your pictureBox1_MouseMove
method to this, you can draw a square with the length equal to the maximum of the width and height:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
endPoint = new Point(e.X, e.Y);
int maxLength = Math.Max(endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
currRect.Width = maxLength;
currRect.Height = maxLength;
}
}
EDIT: Here is the solution that you can use to draw your square from any direction:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
endPoint = new Point(e.X, e.Y);
currRect.X = Math.Min(startPoint.X, endPoint.X);
currRect.Y = Math.Min(startPoint.Y, endPoint.Y);
int maxLength = Math.Max(Math.Abs(startPoint.X - endPoint.X), Math.Abs(startPoint.Y - endPoint.Y));
currRect.Width = maxLength;
currRect.Height = maxLength;
}
}
Upvotes: 3
Reputation: 71
Replace
graphics.DrawRectangle(new Pen(Brushes.Red), currRect.X, currRect.Y, currRect.Width, currRect.Height);
By:
graphics.DrawRectangle(new Pen(Brushes.Red), currRect.X, currRect.Y, Math.Min(currRect.Width, currRect.Height), Math.Min(currRect.Width, currRect.Height));
Secondly, I don't see how the starting point changes?
Upvotes: 1