2

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

我已经创建了一个执行此操作的函数,但它似乎不是很优雅 - 是更好的方法/内置功能吗?

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
4

2 回答 2

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)
于 2013-09-12T15:21:57.147 回答
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
于 2013-09-12T15:23:43.280 回答