【问题标题】:Is there a simpler way to create a positive rectangle from two points?有没有更简单的方法可以从两点创建一个正矩形?
【发布时间】:2013-09-12 15:16:33
【问题描述】:

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

我已经创建了一个可以执行此操作的函数,但它看起来不太优雅 - 是否有更好的方法/内置功能来执行此操作?

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

【问题讨论】:

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


    【解决方案1】:

    大概是这样的

    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)
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2014-12-06
        • 2010-12-17
        • 2012-10-27
        • 2021-06-16
        • 2011-02-16
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多