I have a program where I can, with the mouse, draw a rectangle in any of four directions.
These rectangles are used on a pictureBox to crop parts of an image.
These rectangles must be drawn while maintaining the ratio of a given dimension for example 320 x 200.
I want this tool to behave pretty much exactly like the crop tool in Photoshop, or like in the crop example found here:
https://imageresize.org/
I have most elements working correctly I'm just struggling on a few geometric calculations.
See the "Bottom right" example in my code. This works perfectly and basically I just want to apply this exact formula to the other directions.
I have been playing with different calculations for hours and I just can't seem to work it out.
Here is the working code:
Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs)
'Draw rectangle keeping aspect ratio
If e.Button = Windows.Forms.MouseButtons.Left Then
If e.X > startPos.X And e.Y > startPos.Y Then
'Bottom right
mRect = New Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top)
mRect.Size = New Size(mRect.Width, mRect.Width / Ratio.Text)
If e.Y < mRect.Bottom Then
mRect = Rectangle.FromLTRB(startPos.X, startPos.Y, e.X, e.Y)
mRect.Size = New Size(mRect.Height * Ratio.Text, mRect.Height)
End If
Me.Invalidate()
ElseIf e.X < startPos.X And e.Y > startPos.Y Then
'Bottom left
mRect = New Rectangle(e.X, startPos.Y, startPos.X - e.X, e.Y - startPos.Y)
mRect.Size = New Size(mRect.Width, mRect.Width / Ratio.Text)
Me.Invalidate()
ElseIf e.X > startPos.X And e.Y < startPos.Y Then
'Top right
mRect = New Rectangle(startPos.X, e.Y, e.X - startPos.X, startPos.Y - e.Y)
mRect.Size = New Size(mRect.Height * 1.6, mRect.Height)
Me.Invalidate()
ElseIf e.X < startPos.X And e.Y < startPos.Y Then
'Top left
mRect = New Rectangle(e.X, e.Y, startPos.X - e.X, startPos.Y - e.Y)
mRect.Size = New Size(mRect.Width, mRect.Width / Ratio.Text)
Me.Invalidate()
End If
End If
End Sub
Any help would be hugely appreciated. Thanks!
Below is how things currently work, you can see things go funky when drawing in the north west region. I need to get the same behavior as the south east (or bottom right per the code) for all quadrants.
See Question&Answers more detail:
os