Jamie
Jamie

Reputation: 613

Silverlight Polygon - click within?

I have a Polygon (a Hex for a board game) in Silverlight, something like;

public class GridHex : IGridShape
{
    .....
    public IList<Point> Points { get; protected set; }
    public bool Intersects(Point point) { ... }
}

I would like to be able to say

if(myHex.Intersects(clickedPoint)) { ... }

However I'm unsure of which algorithm to use within the Intersects method - currently I'm using an internal "bounding box" inside each Hexagon to detect if a point is within it, but there must be an algorithm to figure this out? I know the coordinates for the 6 points of each Hexagon.

I was thinking I could maybe create a Silverlight Polygon and do some kind of hit testing? Of course this would be rather memory intensive (I'd be iterating a large number of Hexes to see which Hex a mouse click falls within...) so it might be better to use a mathematical formula to work out if a point is within a Hex....

Upvotes: 2

Views: 987

Answers (2)

Jon Galloway
Jon Galloway

Reputation: 53155

Have you looked into native support using the FindElementsInHostCoordinates? I'd expect this to be faster since it probably utilizes unmanaged code.

Here's a sample which works with vector shapes, supported in Silverlight 2.

And here's an updated sample which utilizes a WriteableBitmap to extend support for hit testing to bitmap images, as well.

Upvotes: 1

T .
T .

Reputation: 4944

This page nicely explains an algorithm for finding out if a point is inside a polygon.

Upvotes: 2

Related Questions