Самый простой способ сдвинуть Rect до границ включенного Rect, когда собирается выйти из него - PullRequest
1 голос
/ 28 сентября 2011

У меня есть Rect A внутри вмещающего Rect B. Вмещающий Rect B - это область, в которой разрешено перемещать Rect A.при попытке переместить Rect A за границы вмещающего Rect B он должен застрять на границе или в углу вмещающего Rect B и больше не двигаться.во время движения у меня под рукой есть следующие параметры: свойства окружающего Rect B, свойства Rect A до перемещения, потенциальная верхняя позиция Rect A после перемещения.Обратите внимание, что перемещение не обязательно для каждого пикселя, оно также может быть (например) 20 пикселей в любом направлении.скажите, пожалуйста, как мне сделать это эффективно, но не слишком сложно?

PS: это просто нарисованные геометрии на холсте в WPF, поэтому использование преобразований также разрешено, но у меня есть только переменные Rect вэтот конкретный бит, а не RectangleGeometries.

1 Ответ

0 голосов
/ 29 сентября 2011

в конце концов я создал включающий Rect для A и B, а затем применил решение в этом вопросе , например:

    private static Point CorrectForAllowedArea(Point previousLocation, Point newLocation, Rect allowedArea, Rect newBox)
    {
        // get area that encloses both rectangles
        Rect enclosingRect = Rect.Union(allowedArea, newBox);
        // 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[] { allowedArea.TopLeft, allowedArea.TopRight, allowedArea.BottomRight, allowedArea.BottomLeft }.ToList();
        // get the first found corner that both rectangles share
        Point sharedCorner = outsideCorners.First((corner) => insideCorners.Contains(corner));
        // find the index of the opposite corner
        int oppositeCornerIndex = (outsideCorners.IndexOf(sharedCorner) + 2) % 4;
        // calculate the displacement of the inside and outside opposite corner, this is the displacement outside the allowed area
        Vector rectDisplacement = outsideCorners[oppositeCornerIndex] - insideCorners[oppositeCornerIndex];
        // subtract that displacement from the total displacement that moved the shape outside the allowed area to get the displacement inside the allowed area
        Vector allowedDisplacement = (newLocation - previousLocation) - rectDisplacement;
        // use that displacement on the display location of the shape
        return previousLocation + allowedDisplacement;
        // move or resize the shape inside the allowed area, right upto the border, using the new returned location
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...