Walt Ritscher: Grappling with Graphics

Exploring Windows Graphics - GDI+, Avalon, and more

  Home :: Contact :: Syndication  :: Login
  10 Posts :: 0 Stories :: 2 Comments :: 1 Trackbacks

Archives

My other blogs

Work

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


posted on Tuesday, March 09, 2004 2:04 PM

Feedback

# re: Creating a normalized rectangle 1/26/2007 9:08 AM Joel
Or the entire body could be this:

Return Rectangle.FromLTRB(
Math.Min(start.X, end.X), Math.Min(start.Y, end.Y),
Math.Max(start.X, end.X), Math.Max(start.Y, end.Y))


Comments Closed! Due to the spam creeps.
If you want to comment, use the contact page and send me an email and the URL of this Post.
Title  
Name  
Url

Comments   
Enter the code you see: