1

我正在编写一个程序,该程序(除其他外)为用户提供了一个类似 IDE 的环境,用户可以在其中使用矩形选择工具选择一个或多个对象。

所有选择都将是一个简单的矩形,所有可选择的对象也将是一个简单的矩形。

我已经有代码 (VB.Net) 可以在视觉上创建橡皮筋效果 - 我需要的是一种有效的算法,它可以告诉我哪些对象在最终选择矩形内至少有一部分区域。

如果它有助于可视化,我想要做的将与在 Windows 桌面上的图标上拖动选择框相同......无论哪个图标的部分区域位于该选择框内,都会突出显示(选中)。

任何帮助将不胜感激......提前谢谢你

4

2 回答 2

0

IntersectsWith就像 BigFunger 已经提到的那样工作。但是另外你应该检查一个矩形是否包含另一个矩形(intersectsWith 只检查相交)。

一个演示它的小样本形式:

Public Class SelectionRectangle
    Private first As Point
    Private allRectangles As New List(Of RectangleF)

    Private Sub form_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseDown
        first = New Point(e.X, e.Y)
    End Sub

    Private Sub form_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseUp
        Dim p As New Pen(Brushes.Black, 2)
        Dim g As Graphics
        Dim second As New Point(e.X, e.Y)
        Dim x, y, w, h As Int32
        x = DirectCast(IIf(first.X > second.X, second.X, first.X), Int32)
        y = DirectCast(IIf(first.Y > second.Y, second.Y, first.Y), Int32)
        w = Math.Abs(second.X - first.X)
        h = Math.Abs(second.Y - first.Y)
        Dim nextRec As New RectangleF(x, y, w, h)
        Dim intersects As Boolean = False
        For Each rec As RectangleF In allRectangles
            If rec.Contains(nextRec) OrElse rec.IntersectsWith(nextRec) Then
                intersects = True
                Exit For
            End If
        Next
        If Not intersects Then
            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot
            g = Me.CreateGraphics()
            g.DrawLine(p, first.X, first.Y, second.X, first.Y)
            g.DrawLine(p, second.X, second.Y, first.X, second.Y)
            g.DrawLine(p, first.X, first.Y, first.X, second.Y)
            g.DrawLine(p, second.X, second.Y, second.X, first.Y)
            allRectangles.Add(nextRec)
        Else
            Beep()
        End If
    End Sub
End Class

更新:将此代码更改为 1.first 检查两个方向和 2. 对您来说更重要的是:还检查一个矩形是否不仅与另一个相交,而且是否包含另一个矩形。

于 2010-11-10T21:39:45.407 回答
0
Dim Rect1 As New Rectangle(10, 10, 20, 20)
Dim Rect2 As New Rectangle(5, 5, 20, 20)

Debug.Print(Rect1.IntersectsWith(Rect2))
于 2010-11-10T21:20:47.050 回答