是否有更简单的方法从两点创建一个正矩形?

时间:2013-09-12 15:16:33

标签: .net vb.net visual-studio-2012 coordinates rectangles

我有两组点,我想从这两个点创建一个总是正的矩形,即最低的坐标对是起点,最高的坐标对是终点。

我已经创建了一个实现此功能但却看起来不太优雅的功能 - 这是一种更好的方法/内置功能吗?

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

2 个答案:

答案 0 :(得分:3)

也许是这样的

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)

答案 1 :(得分:2)

使用Math.MinMath.Abs功能

rX = Math.Min(startX, currentX)
rY = Math.Min(startY, currentY)
rWidth = Math.Abs(startX - currentX)
rHeight = Math.Abs(startY - currentY)

通过分别处理水平和垂直部分,可以简化您的方法:

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