I was looking through some sample code that I will be demonstrating next week at the Software Developer Expo in Santa Clara. (http://www.sdexpo.com) As is often the case while reading through older code I noticed a section that needed refactoring.
Creating a selection rectangle, or lasso, on screen is simple enough. Drawing a rectangle over of the control or image that is under the mouse is usually sufficient. The only issues are determining how to draw the rectangle regardless of what direction your user decides to drag the mouse. There are four possible directions to drag:
- Upper Left to Lower Right
- Upper Right to Lower Left
- Lower Left to Upper Right
- Lower Right to Upper Left
I decided to use the Extract Method pattern and created the NormalizedRect function.
Private Function NormalizeRect(ByVal startingPoint As Point, ByVal endingPoint As Point) As Rectangle
' purpose: Define a rectangle given a starting point and ending point.
' moving left to right, right to left, top to bottom or bottom to top should not matter
Dim topLeftPoint, bottomRightPoint As Point
Dim tempRect As Rectangle
topLeftPoint.X = Math.Min(startingPoint.X, endingPoint.X)
topLeftPoint.Y = Math.Min(startingPoint.Y, endingPoint.Y)
bottomRightPoint.X = Math.Max(startingPoint.X, endingPoint.X)
bottomRightPoint.Y = Math.Max(startingPoint.Y, endingPoint.Y)
tempRect.Location = topLeftPoint
tempRect.Width = bottomRightPoint.X - topLeftPoint.X
tempRect.Height = bottomRightPoint.Y - topLeftPoint.Y
Return tempRect
End Function