Best way of rotating components?

This is what I have, but I’m sure it must be easier to get a vertical component in a particular position …

/** 
 Positions a component, rotated to be vertical, within the area described
 by verticalBounds. 
 */
static void setVerticalRotatedWithBounds(Component * component,
                                         bool clockWiseRotation,
                                         Rectangle<int> verticalBounds)
{
    auto angle = float_Pi / 2.0f;

    if (! clockWiseRotation)
        angle *= -1.0f;

    auto translationX = verticalBounds.getX() + verticalBounds.getWidth() / 2;
    auto translationY = verticalBounds.getY() + verticalBounds.getHeight() / 2;

    component->setTransform(AffineTransform::rotation(angle)
                            .translated(translationX, translationY));

    component->setSize(verticalBounds.getHeight(), verticalBounds.getWidth());
    component->setCentrePosition(0, 0);
}
2 Likes

How about this:

static void setVerticalRotatedWithBounds(Component * component,
                                         bool clockWiseRotation,
                                         Rectangle<int> verticalBounds)
{
    auto angle = float_Pi / 2.0f;
    
    if (! clockWiseRotation)
        angle *= -1.0f;
    
    component->setSize(verticalBounds.getHeight(), verticalBounds.getWidth());  // this line is a bit ugly... and could just look like a typo (it's not, honest)
    component->setCentrePosition(0, 0);
    component->setTransform(AffineTransform::rotation(angle)
                            .translated(verticalBounds.getCentreX(), verticalBounds.getCentreY()));
}

It’s not really much of a saving on what you have but maybe a good compromise. The setSize line isn’t very nice and only works as you’ve specified PI/2. You could do it all ‘properly’ by translating to zero then doing a

setTransform(AffineTransform::scale(something, something).rotated(angle).translated(something, something));

but working out all the somethings would be an even uglier few lines than the setSize line above.

3 Likes

Oh yeah - I figured I was making a bit of a meal of that translationX/Y stuff ;_) Should have drawn a diagram… and no doubt it’d have been more obvious.

Sorry for bumping a super old thread, but this function should actually be as follows. As it is posted it will only work once, the second time you call it, the component will be in the wrong place.

static void setVerticalRotatedWithBounds (Component& component, bool clockWiseRotation, Rectangle<int> verticalBounds)
{
    auto angle = MathConstants<float>::pi / 2.0f;

    if (! clockWiseRotation)
        angle *= -1.0f;

    component.setTransform ({});
    component.setSize (verticalBounds.getHeight(), verticalBounds.getWidth());
    component.setCentrePosition (0, 0);
    component.setTransform (AffineTransform::rotation (angle).translated (verticalBounds.getCentreX(), verticalBounds.getCentreY()));
}
2 Likes