开发者

No matching point found between 2 collections of System.Windows.Points

开发者 https://www.devze.com 2023-04-12 11:00 出处:网络
I have a function where I try to find a matching Point between 2 collections of 4 Points each, but sometimes the function reports the collections do not share a common Point even though in the debugge

I have a function where I try to find a matching Point between 2 collections of 4 Points each, but sometimes the function reports the collections do not share a common Point even though in the debugger I see they do. is the debugger not showing me the full precision of the points so I do not see the difference? or is there something else going on here? here's the code to blame:

public static Point CorrectForAllowedDrawArea(Point previousDisplayLocation, Point newDisplayLocation, Rect displayLimitedArea, Rect newBoundingBox)
{
    // get area that encloses both rectangles
    Rect enclosingRect = Rect.Union(displayLimitedArea, newBoundingBox);
    // get corners of outer rectangle, index matters for getting opposite corner
    var outsideCorners = new[] { enclosingRect.TopLeft, enclosingRect.TopRight, enclosingRect.BottomRight, enclosingRect.BottomLeft }.ToList();
    // get corners of inner rectangle
    var insideCorners = new[] { displayLimitedArea.TopLeft, displayLimitedArea.TopRight, displayLimitedArea.BottomRight, displayLimitedArea.BottomLeft }.ToList();
    // get the first found corner that both rectangles share
    Point sharedCorner = outsideCorners.FirstOrDefault((corner) => insideCorners.Contains(corner));
    // find the index of the opposite corner
    int oppositeCornerIndex = (outsideCorners.IndexOf(sharedCorner) + 2) % 4;

on the last line 's开发者_如何转开发haredCorner' is sometimes set to default(Point) even though both Point collections appear to share 1 Point.

EDIT: I should mention if I place the debugger back to the top of the function and restart it still does not find the matching point. I should also mention that this function uses the Point class of the System.Windows namespace and not of the System.Drawing namespace! Thanks for pointing this out to me in the comments.


We really need to see what the definition of insideCorners.Contains(corner) is, but I suspect that your problem is due to the inherent inaccuracies with floating point numbers.

You cannot compare two floating point values like this:

if (a == b)
{
    // Values are equal
}

especially if either a or b are calculated values.

You'll need to implement something along the lines of:

if (Math.Abs(a - b) < some_small_value)
{
    // Values are equal
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号