Search code examples
codenameone

How do I rotate text string?


How do I rotate a string to 90 degrees? The code doesn't work.

    Transform transform = g.getTransform();
    g.rotateRadians(1.571f);  //90 degree
    x = getX();
    y = getY();
    g.drawString("Title",x,y);
    g.setTransform(transform);

Show nothing(empty)

enter image description here

Remove g.rotateRadians(1.571f); //90 degree

enter image description here

What I want

enter image description here


Solution

  • Based on the code and the screenshots it seems that you're rotating the text outside of the screen bounds as you're rotating from the top left corner to the left of the screen.

    Another problem is clipping boundary, even if you solved the rotation problem through translation this isn't so simple. A component is clipped so you wouldn't be able to accidentally draw outside of its bounds.

    What you need to do is create a component that would be tall enough on the right hand side of the screen (e.g. border layout EAST) and then rotate and translate that.

    Since the coordinate points at the top left position, that would change when drawing vertically. You would need the pivot point of the rotation to revolve around the right area of the component not the left area where the text would normally start.

    See:

    Form hi = new Form("", new BorderLayout());
    Label title = new Label("Title") {
        @Override
        public void paint(Graphics g) {
            int x = getX() + getPreferredH() - getUnselectedStyle().getHorizontalPadding();
            g.translate(x, getY());
            g.rotateRadians(1.571f);
            g.setColor(getUnselectedStyle().getFgColor());
            g.setFont(getUnselectedStyle().getFont());
            g.drawString(getText(), 0, 0);
            g.rotateRadians(-1.571f);
            g.translate(-x, -getY());
        }
    };
    hi.add(BorderLayout.EAST, title);
    hi.show();
    

    Which produces:

    Screenshot of code running