Drawing rotated text revisited.....

Hello again,
I've recently started fiddling with an app that had a method to draw Strings at given Points on a custom JComponent, now I'm trying to extend it to draw the same strings, but throw in an angle should the user choose to do so. But... now here's the part thats foxing me, I want the Point specified to be the center of the String....., i've had a couple of goes, but as soon as the rotation comes in, it goes pair shaped (not literally ;-) , metaphorically).
Here's some of the code I'm working on, feel free to point bad coding and glaringly obvious problems! I'm aware it doesn't quite do "exactly what it says on the tin", but its definitely a step in the right direction. It should work, but it doesn't. Thoughts anyone?
/** Method to draw a text label to a specified graphics context.
     @param g2 The graphics context to draw to.
     @param text The label text to draw.
     @param font The font in which to draw the label.
     @param color The color of the label.
     @param angle The angle at which to draw , 0 = horizontal, 90 = vertical.
     @param position The Point at which to draw the label.*/
public static void drawLabel(Graphics2D g2, String text, Font font, Color color, int angle, Point position)
//get x,y coordinates from Point
int x = new Double(position.getX()).intValue();
int y = new Double(position.getY()).intValue();
//rotate the point by the required angle
x = (new Double((x*Math.cos(Math.toRadians(angle)))-(y*Math.sin(Math.toRadians(angle)))).intValue());
y = (new Double((-x*Math.sin(Math.toRadians(angle)))+(y*Math.cos(Math.toRadians(angle)))).intValue());
// get the current transform
AffineTransform startMatrix = g2.getTransform();
// make a new one...
AffineTransform rotationMatrix = new AffineTransform();
// set the text layout
TextLayout tl = new TextLayout(text,font,g2.getFontRenderContext());
// rotate the shiny new transform
rotationMatrix.rotate(Math.toRadians(angle));
// appy it to g2
g2.transform(rotationMatrix);
//set the color of the label
g2.setPaint(color);
//draw the label
tl.draw(g2,x,y);
//restore the transform for g2
g2.setTransform(startMatrix);
}Also I haven't sorted the drawing relative to the center of the string bit yet, so any advice on how to do this would be great.
Cheers,
Tom

This is straightforward, once you understand transforms. I'm surprised no one's answered this yet. Here's an example:
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
public class TestRotate extends Frame {
    public static void main(String[] args) {
        new TestRotate().setVisible(true);
    private TestRotate() {
        super("Rotated Text");
        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
        setFont(new Font("default", Font.PLAIN, 24));
        setSize(300, 300);
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        TextLayout layout = new TextLayout(
            "This is a string to rotate",
            g2d.getFont(),
            g2d.getFontRenderContext());
        Insets ins = getInsets();
        Dimension dim = getSize();
        Point center = new Point(
            ins.left + (dim.width - ins.left - ins.right) / 2,
            ins.top + (dim.height - ins.top - ins.bottom) / 2);
        g2d.translate(center.x, center.y);
        g2d.rotate(Math.PI / 4);
        layout.draw(g2d, -layout.getAdvance() / 2, 0);

Similar Messages

  • Errors - drawing a text curve in flex with flex 3 with flex 3.5 framework

    Is that necessary in drawing a text curve in flex we need flex 4 with flash player 10, actually i have flex 3 with flex 3.5 framework but it is showing error like this :
    This is my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.components.TextView;
    public var myText:String = "Read my blog @ http://www.funnyjokesfunny.com";
    var radius:Number = 125;
    var spacing:Number = 8;    
    var center:Point = new Point(125,125);
    public function drawText():void {
    for (var char:uint=0;char<myText.length;char++) {
    var tempText:TextView = new TextView();
    tempText.x = radius * Math.cos(degrees2radians(char*spacing)) + center.x;
    tempText.y = radius * Math.sin(degrees2radians(char*spacing)) + center.y;
    tempText.rotation = 25;
    tempText.text = myText.charAt(char);
    textContainer.addChild(tempText);
    ]]>
    </mx:Script>
    <mx:Button label="Draw a circle" click="drawText()" />
    <mx:Canvas id="textContainer"  y="50" x="50"  width="400" height="400" />       
    </mx:Application>
    1) call to possibly  undefined method Text View
    2) Type was not found : Text view.                               
    Please help me
    Atishay

    I have now taken import mx.controls.Text;
    instead of textview it works , but in dis example http://blog.shortfusion.com/index.cfm/2009/1/25/Circular-Text-In-Flex-Explained with source code they have taken textview control and it works for them for text curve.

  • Rotating text without embedding fonts - how?

    No doubt same or similar question was asked and most likely answered but I could not
    find anything that would match...
    I want to draw column headers of my ADG vertically. So, I need rotate column text 90 degree
    and adjust position.
    Is it true that it can be achieved with embedded font only? If it is true how can it be done for
    Unicode code, which includes ranges for Japanese, Chinese, etc characters. The size of
    swf is going to be huge. Several sites like this
    http://www.forestandthetrees.com/2009/06/29/rotating-text-without-embedding-fonts/
    claims that they have a solution for the problem without embedding fonts.
    Note: I am still using Flex 3.3 SDK with no TLF. By the way, do TLF libraries work with
    3.3 SDK.?
    Thanks in advance

    Draw your text onto a bitmap image (or take an ImageSnapshot of a Label), then rotate the image.

  • Cannot rotate text in table cell

    I am using LiveCycle Designer 8. I want to rotate the text in the top row of a table so that the text is displayed vertically. I have created a simple 3 column, 2 row table. I select one of the cells in the top row (I click in the cell and the cell borders are highlighted). When I go to the "Layout" tab the "Rotate to 90", "Rotate to 180" and "Rotate to 270" buttons are "active" (meaning they are not greyed out and when I click on them, they move just as you would expect a button to move). The problem is that the cell does not rotate when I click on any of those three buttons. It's as if Designer simply ignores my click.
    Since I am relatively new to Designer, my first question is: am I going about this correctly? If not, how do I rotate text vertically in a table? If I am doing it correctly, what can I do to fix this problem?
    Thanks.

    Tim, you're not doing anything wrong.  That was a bug in Designer 8 that has since been fixed.  <br /><br />To get around your problem, try manually adding rotate="90" to that particular cell in the XMLSource.<br /><br />So you would have something like:<br /><draw w="30mm" h="22.2238mm" name="Cell1" rotate="90"><br /><br />Steve<br />Adobe Systems

  • Drawing verticle text

    any one know how to use the paint method to draw verticle text. I search in the forums couldnt find anything. I would assign duke dollars for this but it wont let me.
    thanks.
    Kevin

    If you want to draw real oriented text, try this:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    public class VerticalLabelTest extends JFrame {
       public static void main(String[] args) {
          JLabel label1 = new JLabel("100,100 Label text (normal)");
          label1.setSize(200, 20);
          label1.setLocation(100, 100);
          JLabel label2 = new JLabel("100,100 Label text (rotated 90�)");
          label2.setUI(new VerticalLabelUI(true));
          label2.setSize(200, 20);
          label2.setLocation(100, 100);
          JLabel label3 = new JLabel("120,120 Label text (rotated -90�)");
          label3.setUI(new VerticalLabelUI(false));
          label3.setSize(200, 20);
          label3.setLocation(120, 120);
          JPanel pmain = new JPanel();
          pmain.setLayout(null);
          pmain.add(label1);
          pmain.add(label2);
          pmain.add(label3);
          JFrame fmain = new VerticalLabelTest();
          fmain.setSize(500, 500);
          fmain.getContentPane().add(pmain, BorderLayout.CENTER);
          fmain.setVisible(true);
    class VerticalLabelUI extends BasicLabelUI {
       static {
          labelUI = new VerticalLabelUI(false);
       protected boolean clockwise;
       VerticalLabelUI( boolean clockwise ) {
          super();
          this.clockwise = clockwise;
       public Dimension getPreferredSize(JComponent c) {
          Dimension dim = super.getPreferredSize(c);
          return new Dimension( dim.height, dim.width );
       private static Rectangle paintIconR = new Rectangle();
       private static Rectangle paintTextR = new Rectangle();
       private static Rectangle paintViewR = new Rectangle();
       private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
       public void paint(Graphics g, JComponent c) {
          JLabel label = (JLabel)c;
          String text = label.getText();
          Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
          if ((icon == null) && (text == null))return;
          FontMetrics fm = g.getFontMetrics();
          paintViewInsets = c.getInsets(paintViewInsets);
          paintViewR.x = paintViewInsets.left;
          paintViewR.y = paintViewInsets.top;
          // Use inverted height & width
          paintViewR.width  = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
          paintViewR.height = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
          paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
          paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
          String clippedText = layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
          paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
          paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
          Graphics2D g2 = (Graphics2D) g;
          AffineTransform tr = g2.getTransform();
          int wh = paintViewR.width;
          if (wh < paintViewR.height) wh = paintViewR.height;
          g2.setClip(0, 0, wh, wh);
          if (clockwise) {
             g2.rotate( Math.PI / 2 );
             g2.translate( 0, - paintViewR.width );
          else {
             g2.rotate( - Math.PI / 2 );
             g2.translate( - paintViewR.height, 0);
          if (icon != null) icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
          if (text != null) {
             int textX = paintTextR.x;
             int textY = paintTextR.y + fm.getAscent();
             if (label.isEnabled()) {
                paintEnabledText(label, g2, clippedText, textX, textY);
             else {
                paintDisabledText(label, g2, clippedText, textX, textY);
          g2.setTransform(tr);
    }Hope this helped,
    Regards.

  • Missing rotated text in PDF created via FPDF

    Hi guys,
    I have a weird problem which is preventing some rotated text to be viewed in adobe reader, while every other reader like foxit, google pdf viewer and scrib are doing just fine!
    if you create a flyer using following link
    http://www.erupert.ca/classifieds/create_flyer/ad/32_1306248214
    the generated PDF displays just fine in google document viewer but if I download and open the same in Adobe reader the pull tab text (text rorated 90 degrees) vanish, again the PDF is just fine in foxit reader as well!
    What am I doing wrong, any ideas would be much appriciated.
    Also here is the code to rotate text I'm using by extending the FPDF class
    function Rotate($angle,$x=-1,$y=-1)
    if($x==-1) $x=$this->x;
            if($y==-1) $y=$this->y; //echo "{$this->x} - {$this->y}";die();
            if($angle!=0) $this->_out('Q');
            $angle=$angle;
            if($angle!=0)
    $angle*=M_PI/180;
    $c=cos($angle);
    $s=sin($angle);
    $cx=$x*$this->k;
    $cy=($this->h-$y)*$this->k;
    $this->_out(sprintf('q %.5f %.5f %.5f %.5f %.2f %.2f cm 1 0 0 1 %.2f %.2f cm',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy));
    OS: Windows Any ( >= XP)
    Adobe version X (latest updates)
    Thanks,
    Anupam

    Hello anupam,
    I know this is a particularly old thread, however i thought i'd post the solution here for others who may have been searching around for a solution to this very same problem and come across this thread.
    As George has correctly stated it is an issue with the unbalanced q and Q operators. I recognise the provided piece of code, it is of course a snippet from a generation class such as FPDF or TCPDF or HTML2PDF, the error occurs when the rotation is not returned to 0 before finalising the document.
    i.e. You would have used something like $pdf -> Rotate(270,60,50) or $this -> Rotate(270,60,50) where 270=the degree of rotation , 60=the x coordinate , 50=the y coordinate.
    Once you've completed writing all your text, lines, images, cells you need to make sure to reset the rotate i.e. $pdf -> Rotate(0) prior to Outputting the pdf to screen or saving it as a file.

  • How do I rotate text within a table Pages 4.3?

    Does anyone know how to rotate text within a cell in a Pages 4.3 table?

    You would have to use a floating text box over the cell. Make sure text wrap is turned off.

  • Cannot edit text in Drawing Markup Text Box

    I cannot edit text in Drawing Markup Text Box after saving and closing the pdf file and then reopening it.  I go to add additional text in the Text Box, and nothing happens.
    Hope you can lend me a hand,
    Richard
    Adobe X Pro 10.1.4

    In the previous print screen, the layer icon has a paintbrush in it. In the new menu page I cut and pasted the text is still 'text' layer. I am not able to format it other than change font color. I want to make it two columns of text like the original pdf, and change the font.

  • Can't change rotating text on revoltion theme after I delete the menu text.

    So I export a slideshow to iDVD. By default you have the revolution theme. There is text that says revolution main in the body of the menu and it says revolution main on the rotating text. There is also a button for my slideshow. So I change the revolution main text to what I want the rotating text to be then delete that text on the main menu. The rotating text then stays. But if I want to then change it, I can't see any way to do so because I deleted the button. What was it that I deleted? How do I get it back. I thought it was the title menu, so I add a new title menu button and try to change the text but the rotating text won't change. I am probably missing something simple, but I can't for the life of me figure it out.
    Thanks in advance,
    Brian

    Hi,
    Count me in.
    Same issue,
    Once deleted the title can't [it appears] be changed from the default of 'Revolution Extras' .. which is a nuisance as the rest of the project I'm working on is finished ... I thought i'd wait till the end to name it but find I am struggling to find out how.
    can anyone help?
    kindest,
    becca

  • In pages, how can I rotate text ?

    In pages, how can I rotate text ?

    The text needs to be in a TextBox which you can create from the ToolBar and the that can be rotated by control clicking near the top right corner of TextBox and dragging it around.
    Alternatively click on the TextBox > Inspector > Metric > Rotate: enter value.
    Peter
    Greetings from hot, sweaty and beautiful Broome

  • How to rotate text

    I was told to restate my number's problem as I want to rotate text within a single cell. This is for grade book so the column label can be hidden along with other data.

    ohsster,
    I was also excited by iWorks, and I was planning to adopt it and try to wean myself from Office even before Numbers was announced. I figured I'd just use the Tables within Pages to do my spreadsheet functions, since all the same calculations are available there. After a month of working in iWork, it's obvious that it would be premature to un-install Office for Mac, but I'm still determined to make the switch and I believe that Apple will address the serious issues, like the speed problem, in short order. So, I'm still excited about being closer to shaking the Microsoft dependency.
    Regarding your application, I don't know how large and complicated your design is, but I encourage you to try my suggestion just to get a feel for working with references that span sheets and tables. This, to me, is much easier in Numbers than in Excel. I tried cross-sheet referencing in Excel years ago and found it too complicated, but in Numbers it is as simple as pie. You can build your second table in the same sheet as your first table if you want to keep things close together for that phase, and then just drag the new table to a new sheet when you're done with it. To make a cell in the destination table mirror the entry in the source table, simply type an = sign in the destination cell and then click on the source cell. To replicate the reference in the first destination cell across the first row, highlight that cell and drag the fill handle across the row. Then, with the filled row highlighted, drag the fill handle down the sheet to populate as many rows as you need. This whole process takes only a few seconds. Now you have a copy of the source table that can be independently formatted, labeled and printed after you move it to it's own sheet. This is the Numbers equivalent of setting a Print Area in Excel, except on steroids.
    I hope you don't give up!
    Jerry

  • Aligning rotated text away from spine

    I am creating a directory which rotated text towards the edge of the page. This is so that people can thumb through it and quickly get to their section of interest. When I insert a page, the edge becomes spine. I need the text box to automatically turn 180 and move towards the edge. Is this possible?

    If I'm understanding you, you can cause such a frame stay away from the spine if you make it an anchored object which is anchored to the text which includes the faculty email. In Object > Anchored Object Options, you need to choose the Relative to Spine option. I made the text of the faculty page red to see what happens when a page is added. Here's the way it's created. You can see where it's anchored because I turned on View > Extras > Show Text Threads. The frame is anchored at the beginning of a paragraph.
    After adding a page the anchored object stays away from the spine:
    However, I think you'd have to manually rotate the frame (unless it could be done with a script). The text frame is oriented in the same direction on both left and right pages.

  • Rotate/rotating text in SmartForms

    Need to rotate text 90 degrees in a SmartForm.
    The printers are all PCL based.
    New print-controls cannot be created.
    In PCL, the following command sets rotation:
    <ESC>&a#P
    where # is the number of degrees
    To rotate 90 degrees, the PCL command would be:
    <ESC>&a90P
    In SAPscript, I can use the print-control for <ESC>.
    /:  PRINT-CONTROL SESCP
    =  &a90P
    Another method that works involves standard texts.
    Define standard texts named ZPCLROTATE90 and ZPCLROTATE0.
    They willl set the rotation to 90 and reset to 0 degrees.
    /: PRINT-CONTROL SESCP
    ( &a90P
    /: PRINT-CONTROL SESCP
    ( &a0P
    The SAPscript uses the new standard text objects:
    AS  horizontal text
    /:  INCLUDE ZZPCLROTATE90 OBJECT TEXT ID ST
    AS  rotated text
    /:  INCLUDE ZZPCLROTATE0 OBJECT TEXT ID ST
    AS  horizontal again
    This also works in SAPscript.
    None of this seems to work in SmartForms.  I thought the INCLUDE text would work the same in SmartForms.  It does not.
    Tried the first method shown; SmartForms converts the "=" or "(" paragraph symbol to "*".  This separates the escape sequence and it becomes invalid.
    Any ideas?  They do not want to use SAPscript.  Cannot create a Z print-control.
    Thanks,
    Norm

    Hi,
       Try to follow the steps givenbelow in your SMARTFORM.
    1. Create a template and keep the text alone inside that you wanted to rotate.
    2. Above and Below your text, In the text element that you wanted to rotate give the Print control.
    Ex PRINT CONTROL 'SF201'
         &variable text&
        PRINT CONTROL'SF202'
    2. Create a command inside the window and enter the attribute name and the attribute value.
        Ex. Use Attribute name as S_LZPL_HR1
                     Attribute value as 'BC_CD39'
    3 Create another command above the template and enter the value "SF200" in Include Printer control.
    4.Create another command above the template and enter the value "SF202" in Include Printer control.
    I followed the above procedure for rotation of texts, and it worked.
    Thanks
    Narasingam

  • Jagged edges on rotated text in Flash

    Does anyone have a good solution for getting rid of jagged edges on rotated text? I have tried the anti-aliasing options but nothing seems to change the jaggedness.
    Any advice is apprecitated.
    Thanks!

    I don't know if this is the problem, but I've seen some display anomalies when using the scroll wheel on the mouse (typically sideways scroll, but it happens with vertical sometimes, too). I know Logitech mice are affected, but I don't believe it's resticted to just the Logitech mice. Im most cases switching to the Hand tool (use the keyboard shortcut Alt/Opt + Spacebar to access it temporarily) and clicking will clear things up again, sometimes for the rest of the editing session. When I see this, though, it affect all pages not just one.
    Does the type clear if you restart ID and reopen the file?

  • Unable To Use Flash Drawing Or Text Tools--Help!

    I'm a Flash CS4 user and two days ago started having a strange problem--when I use any of the drawing or text tools in
    Flash, my work disappears as soon as I let go of the mouse button! I've tried reinstalling Flash and that didn't work, and I can't think of any internal settings that could be causing this. And strangely, I'm running Fireworks CS4 on the same computer and am not having any problems with it. Has anyone experienced this? Any help would be appreciated.

    Flash Player 12.0.0.43 Plug-in (All other browsers)
    First, use the Flash Player Uninstaller

Maybe you are looking for