Reputation: 27322
I have two sets of points, I want to create a rectangle from these two points that is always positive i.e. the lowest co-ordinate pair is the start point and the highest co-ordinate pair is the end point.
I have created a function that does this but it doesn't seem very elegant - is the a better way/built in functionality to do this?
Private Function CalculateDraggedRectangle(ByVal startX As Integer, ByVal startY As Integer, ByVal currentX As Integer, ByVal currentY As Integer) As Rectangle
Dim rX, rY, rWidth, rHeight As Integer
If currentX < startX Then
If currentY < startY Then
rX = currentX
rY = currentY
rWidth = startX - currentX
rHeight = startY - currentY
Else
rX = currentX
rY = startY
rWidth = startX - currentX
rHeight = currentY - startY
End If
Else
If currentY < startY Then
rX = startX
rY = currentY
rWidth = currentX - startX
rHeight = startY - currentY
Else
rX = startX
rY = startY
rWidth = currentX - startX
rHeight = currentY - startY
End If
End If
Return New Rectangle(rX, rY, rWidth, rHeight)
End Function
Upvotes: 2
Views: 595
Reputation: 112259
Use the Math.Min
and Math.Abs
functions
rX = Math.Min(startX, currentX)
rY = Math.Min(startY, currentY)
rWidth = Math.Abs(startX - currentX)
rHeight = Math.Abs(startY - currentY)
Your approach can be simplified by treating the horizontal and vertical parts separately:
Private Function CalculateDraggedRectangle(ByVal startX As Integer, ByVal startY As Integer, ByVal currentX As Integer, ByVal currentY As Integer) As Rectangle
Dim rX, rY, rWidth, rHeight As Integer
If currentX < startX Then
rX = currentX
rWidth = startX - currentX
Else
rX = startX
rWidth = currentX - startX
End If
If currentY < startY Then
rY = currentY
rHeight = startY - currentY
Else
rY = startY
rHeight = currentY - startY
End If
Return New Rectangle(rX, rY, rWidth, rHeight)
End Function
Upvotes: 2
Reputation: 148980
Perhaps something like this
Dim rX = Math.Min(startX, currentX)
Dim rY = Math.Min(startY, currentY)
Dim rWidth = Math.Abs(startX - currentX)
Dim rHeight = Math.Abs(startY - currentY)
Return New Rectangle(rX, rY, rWidth, rHeight)
Upvotes: 3