Davoud
Davoud

Reputation: 27

how can find which object is over others

I have a class(shape) for draw custom shape on a canvas that I made it before. For checking mouse pointer is over a shape I used canvase_mousemove event and into a loop I check shape.region.invisible(e.location) is true or not.(if true means mouse is over of shape). But when two or more objects are overlaped, "shape.region.invisible(e.location)" are true and I can not find which one is top of others.

in shape class:

Private _shapeRegion As Region
Public ReadOnly Property Region() As Region
    Get
        Return _shapeRegion
    End Get
End Property

Public Sub DrawShape(ByVal point As PointF, ByVal size As SizeF, ByRef graphics As Graphics)
    _shapePath = New GraphicsPath
    _shapePath.AddEllipse(New RectangleF(point, size))
graphics.DrawPath(_basePen, _shapePath)
graphics.FillPath(_baseBrush, _shapePath)
_shapeRegion = New Region(_shapePath) 
End Sub

in canvas:

 Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
    MyBase.OnMouseMove(e)
    For Each _shape As Shape In _canvasShapes
    _shape.Highlight=_shape.Region.IsVisible(e.Location)
        _shape.ApplyProperties()
    Next
    Me.Invalidate()
End Sub

enter image description here

Upvotes: 1

Views: 59

Answers (1)

selfstudy
selfstudy

Reputation: 523

I assume that you draw shapes in order of their appearance in the shapes list, so you first draw shape 0, then shape 1 and so on.

So the shape with greater index is the shape on top and you can use a reverse For loop to find it:

Dim selectedIndex = -1
For index = shapes.Count-1 To 0 Step -1
    If(shapes(index).IsVisible(Point.Empty)) Then
        selectedIndex = index
        shapes(index).Highlight = True
        Exit For
    End If
Next
' selectedIndex contains the selected index

I also recommend using Using when creating GraphicsPath and Region, for example, when creating IsVisible:

Public Function IsVisible(pt As Point) As Boolean
    Using p As New GraphicsPath
        p.AddEllipse(New Rectangle(Location, Size))
        Return p.IsVisible(pt)
    End Using
End Function

Upvotes: 1

Related Questions