Rectangle Placement


#1

If I have a component (e.g. a label) that I want to place near a target component, but not overlapping it, but within the parent component, is there an existing algo in JUCE somewhere? 


#2

Hmm.. Not really. There are various places where I've done that internally, e.g. for PopupMenu, CalloutBox etc, but never pulled it out into a stand-alone algorithm. It's a good request, actually.


#3

    /**
     Finds a rectangle within constainingArea, near targetObject of size
     'width' and 'height', separated by a distance of 'padding'.  
     
     Prefers a position centered and above the target object. 
     */
    Rectangle getPlacementNear(Rectangle targetObject,
                                    Rectangle constrainingArea,
                                    int width, int height, int padding)
    {
        /* Put the object in the best possible place. Centred above the target object
         and spaced with 'padding' */
        
        auto location = Rectangle(0, 0, width, height)
        .withY(targetObject.getY() - (height + padding))
        .withX(targetObject.getCentreX() - (width / 2));
        
        /* Move it elsewhere if it doesn't fit ... */

        if (location.getX() < constrainingArea.getX())
            location.setX(constrainingArea.getX());
        
        if (location.getRight() > constrainingArea.getRight())
            location.setX(constrainingArea.getRight() - width);
        
        if (location.getY() < constrainingArea.getY())
            location.setY(targetObject.getBottom() + padding);
        
        return location;
    }

Works well for my current needs (centred and above) but isn't generic enough really ...