ScrollRectIntoView for Viewport


#1

It took my somehow quite long to come up with this usefull code snippet, so maybe other might find it handy.

The scrollRectIntoView makes sure that the rect you passed in will be visible in the viewport. It might be a nice addition to the Viewport class itself.

void scrollRectIntoView(Viewport& viewport, const Rectangle<int>& rect, const Point<int>& margin )

{

    Rectangle<int> viewRect(viewport.getViewPositionX(),

                            viewport.getViewPositionY(),

                            viewport.getViewWidth(),

                            viewport.getViewHeight());

    

    

    if (!viewRect.contains(rect.reduced(margin.getX(), margin.getY())))

    {

        int deltaX = 0;

        int deltaY = 0;

        if (rect.getRight() > viewRect.getRight())

        {

            deltaX = rect.getRight() - viewRect.getRight();

        } else if (rect.getX() < viewRect.getX()) {

            deltaX = rect.getX()- viewRect.getX();            

        }

        

        if (rect.getY() < viewRect.getY())

        {

            deltaY = viewRect.getY() - rect.getY();

        } else if (rect.getBottom() > viewRect.getBottom()) {

            deltaY = viewRect.getBottom() - rect.getBottom();

            

        }

        

        viewport.setViewPosition(viewport.getViewPositionX()+deltaX,

                                 viewport.getViewPositionY()-deltaY);

    }

}

#2

+1


#3

That code seems rather chaotic.. couldn't it be done in a couple of lines of code by using Rectangle::constrainedWithin() ?


#4

"constrainedWithin" interesting function indeed!


#5
static void scrollRectIntoView(Viewport& viewport, const Rectangle<int>& rect, const Point<int>& margin )
{
    Rectangle<int> viewRect(viewport.getViewPositionX(), viewport.getViewPositionY(), viewport.getViewWidth(), viewport.getViewHeight());
    Rectangle<int>rectWithMargins = rect.expanded(margin.x, margin.y);

    Point<int> movedBy = rectWithMargins.constrainedWithin( viewRect ).getPosition() - rectWithMargins.getPosition();

    viewport.setViewPosition(viewport.getViewPosition() - movedBy);
}