Text shifts while drawing using Graphics2D, TextLayout and AffineTransform

Hi,
Text is drawn to Panel using Graphics2D, TextLayout and AffineTransform. A rectangle is drawn around the text where one side of rectangle touches text. When I rotate Text and Rectangle by 90 degrees around the center, text is shifted by one pixel away from the side of the rectangle.
Please see the below code: For rotation change the angle from 0 to 90
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawText extends JPanel {
     public DrawText() {
          setBackground(Color.white);
          setSize(350, 400);
     private static void adjustGraphics(Graphics2D g) {
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
          g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                    RenderingHints.VALUE_FRACTIONALMETRICS_ON);
          g.setRenderingHint(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
     public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          adjustGraphics(g2);
          g2.setColor(Color.black);
          String toPrint = "Draw Text Test!";
          double nX = 100, nY = 100, width = 100, height = 0;
          double angle = 0;// Change the angle from 0 to 90
          angle = Math.toRadians(angle);
          FontMetrics fm = this.getFontMetrics(g2.getFont());
          height = fm.getHeight();
          AffineTransform afNew = new AffineTransform();
          afNew.rotate(-angle, nX + width / 2.0, nY + height / 2.0);
          g2.setTransform(afNew);
          g2.draw(new Rectangle2D.Double(nX, nY, width, height));
          nY = nY + (fm.getAscent() - fm.getLeading());
          AttributedString attStr = new AttributedString(toPrint);
          attStr.addAttribute(TextAttribute.FONT, g2.getFont());
          TextLayout textLayout = new TextLayout(attStr.getIterator(), g2
                    .getFontRenderContext());
          nX = nX - textLayout.getBounds().getX();
          textLayout.draw(g2, (float) nX, (float) nY);
     public static void main(String arg[]) {
          JFrame frame = new JFrame();
          frame.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                    System.exit(0);
          frame.getContentPane().add("Center", new DrawText());
          frame.pack();
          frame.setSize(new Dimension(350, 400));
          frame.setVisible(true);
}

Include a timer that slowly increases the the angle from 0 to 90 and repaints each time. You'll notice that at some angles the "D" is flushed with the rectangle, while at other angles (like 90) it's offset by one pixel. If you look at all the letters at once, though, you'll notice they shake about quite a bit. Sometimes one letter is closer to another letter, while other times they're farther apart. A screenshot of any given angle looks OK, but when in slow motion you see just how inexact text rendering under a transformation may be.

Similar Messages

  • I just purchased my Macbook Pro retina display OS X 10.7.4 in June 2012. Shortly after I began using it, it began randomly restarting itself while in use. Why and how do I fix this?

    So as I said in the title, I purchased my new Macbook Pro retina display OS X 10.7.4 in June 2012 and recieved in early July. Shortly after I started using the laptop, it began randomly restarting itself. It does this about once a week while I am just using the laptop for normal internet browsing. I haven't downloaded any outside software that the system could be rejecting and it is fully charged. Any ideas on why this is happening or how to fix it?
    Also this is a total random question, but there is a residue on my laptop that is faint but randomly shows up. I'm almost positive that it is nothing on my hands or where I place the laptop. I wasn't sure if it was something possibly coming from the side vents. Thanks for the help!

    Exactly what Shootist007 states - take it in for service or replacement - could be a simple software issue or it could be a hardware issue...
    Don't even bother messing with it.....Might screw up even more.....
    Make sure your files are backed up in case they give you a replacement....
    Good luck - hope you get it sorted out...

  • Can I text to an iphone using mountain lion and macbook pro?

    Just wondering if I can text from my macbook pro using mountain lion with the new messages app? What i've read seems to say that you can text to any imessages user.  Does this mean that a text can go from my messages app in mountain lion on my computer to an iphone using imessage? Thanks!

    Hi,
    You have to have an Apple ID on Messages on the Mac to get it to start.
    Once that is done it will also tend to find all the iChat Accounts you may have had.
    Uploaded with Skitch!
    I have several names that have "me" in the name that Messages thinks are iMessages accounts (see icons).
    I also have AIM (AOL) accounts.
    My Google ID is a Jabber account.
    The iPhone has to be set up in Settings > Messages > Received At > Caller ID
    As has been mentioned in this thread the Messages option has to be on.
    A New Message icon starts things and then you chose a Contact for iMessages
    Uploaded with Skitch!
    It indicates if you are using iMessage or AIM or Jabber to Contact people.
    The "To" spot becomes a drop down when a  name is there (you can then change to an Apple ID or Phone number or Switch to an AIM Screen Name or Jabber ID if the Contact (Address Book) Card has the details
    Uploaded with Skitch!
    As you can see I have an @mac.com and an @me.com name logged in and could switch to AIM logins to contact "myself" as a Buddy (rather than an iMessage Contact)
    10:34 PM      Sunday; August 5, 2012
    Please, if posting Logs, do not post any Log info after the line "Binary Images for iChat"
      iMac 2.5Ghz 5i 2011 (Lion 10.7.2)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
    "Limit the Logs to the Bits above Binary Images."  No, Seriously

  • Is there any way to create another Apple ID while still using billing information and purchases from a previous one?

    We have 5 iDevices on one account and I cannot use features like iCloud without mixing information with the rest of my family. We've made due for years, but it's getting very tedious. I would love to have my own ID and password but still be able to be under my parents' billing information. (The more I think about it, the more I begin to doubt the liklihood of the possibility)
    At the very least, is there a way I can create a new ID and keep/transfer the purchases (and all other information like contacts, notes, etc.) I've made on the original account without starting over?

    For Family Sharing, why must I add a credit card to add a child? Please explain why my debit card, on file, isn't enough…
    Create an iTunes Store, App Store, or iBooks Store account without a credit card or other payment method - Apple Suppor…
    Family Sharing and Apple IDs for kids - Apple Support
    Set up and manage iTunes Allowance - Apple Support

  • Can I Turn off iMessage in a group text with multiple people with different devices? There's 1 person in the group text that doesn't use iPhone anymore and they can't see any messages that are sent unless we send as regular text individually.

    Is there a way to turn off iMessage for a group text that includes multiple people with different non-apple devices? When a message is sent, only the iPhone users can see the iMessage. Those without them cannot see the texts unless we send individual Text Messages or turn off iMessage completely.

    now I have this and it still doesn't work.
    Section "ServerLayout"
    Identifier "Simple Layout"
    Screen "Screen 1" 0 0
    InputDevice "Mouse1" "CorePointer"
    InputDevice "Touchpad" "SendCoreEvents"
    InputDevice "Keyboard1" "CoreKeyboard"
    Option "OffTime" "1"
    EndSection
    Section "ServerFlags"
    Option "AutoAddDevices" "False"
    Option "DontZap" "false"
    EndSection

  • With iOs 7 and the iPhone can someone use the phone while also using a communication app such as Speak It or Assistive Chat? These are text to speech systems for people who cannot speak well. Thanks you!

    With ios 7 and the iPhone can someone use their phone while also using a text to speech app, such as Speak It or Assistive Chat? These apps are used by people who have difficulty with speech production.
    Thank you.

    My iPhone 5 wouldn't start after I turned it off a few minutes after writing this. It went into recovery mode and I had no choice but to connect to iTunes on PC and restore.
    I restored to factory setting first, just to validate my phone was okay. For a second consecutive iOS update, the  iPhone 5 did not update smoothly while connected to PC and iTunes - I had to retry two times before the progress bar for the update showed. (The exact same problem with the restart occured when I updated to 7.0.4.)
    The good news is that I was ultimately able to restore the iPhone 5 to factory settings while running iOS 7.0.6. I did have a backup from about a month ago lying around and was able to successfully restore with that as well, so the damage done is almost negligible since I had my contacts, notes, mail, etc. backed up to iCloud.
    Once I completed both restores, the sync with iTunes worked fine.

  • I received a text today while at work about iCloud keychain verification code. I have not signed up for it or anything that uses it. I work out of the city with limited internet access so not sure why I would be getting this. Is my info safe??

    I received a text today while at work about iCloud keychain verification code. I have not signed up for it or anything that uses it. I work out of the city with limited internet access so not sure why I would be getting this. I only got this number about a month ago. Apparently someone else had the number before because I get texts from his family members wondering whats going on. I got one yesterday and the person didn't seem to thrilled that the number was cutoff and today I got 2 texts about iCloud Keychain which I don't even know what it is. Seems suspicious to me. If the person who use to own the number is doing it he should know it is not his number anymore because he obviously didn't pay his bills.  I'm not too sure about iCloud Keychain so just want to know my info safe?? It says it can store credit card numbers which is what gets me worried. Frankly I think it's pretty stupid to save that kind if information with any kind of app. But I don't want some random person trying to access my personal information because they are bitter they lost their number.  Please let me know as soon as possible so I can change passwords or anything that is needed.
    thanks

    If it were me, I would go to my carrier and get a new number. Since you have only had it for a month, the inconvenience would be minimal.
    Barry

  • Is there a way to stop the text shifting between mac and pc?

    I can't believe there is still no fix to the vertical text shift issue when transferring fla's between Mac and PC's. Create an fla on a Mac put some text in it, save the file and open it on a PC and see how the text has dropped.
    Adobe please tell me I'm missing something here or at least acknowledge the problem and explain the cause.
    This problem has plagued flash for as long as I can remember. None of the other applications (Photoshop, Illustrator etc) have this problem. It wastes huge amounts of time and causes massive quality control issues especially when outsourcing work.
    We're using CS3 now and the problem is as bad as ever. It happens with all text fields and all font types.
    Please help.

    Don't get your hopes up that anyone from Adobe will see your posting.  These are user to user forums and appearances by anyone from Adobe are rare.
    suggestions to Adobe - Wishlist
    http://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

  • I want to make gImage Class extends Image and use Graphics2D

    Sorry, my english short...
    I want to make gImage Class extends Image and use Graphics2D
    I trying to do...
    make class gImage..
    extends Image class. (Inheritance)
    but Image class is abstract class..
    And I want to use gImage class same as Image class.
    I can't use constructor... because by Abstract calss...
    How do i?
    Help me.. plz...
    And I want to use Graphics2D at Applet Game, But not use Java JDK Plug-in...
    No Way?

    You need to use BufferedImage with 2D or RenderedImage with JAI.
    BufferedImage effectivley extends an Image so you can
    draw it to screen in paintCOmponent.
    I use an Extended JPanel to draw an image in a Panel with this.
    MArk

  • IPhone 4 does not notify me of a text message while I am using another app

    What gives?? I have not changed any settings on my iPhone but I recently noticed that when I am actively using another app (any app from social networking to games, etc.) my phone does not vibrate/ring/otherwise notify me that I have received a text. The only way I can tell if I have received a text is if I exit an app, then scroll over to my messages and see if there is an icon to show that I have a new message. How can I fix this? When I am not using my iPhone for anything else, my text message notifications work fine. Thanks for your help!

    Nope, text messages are set to alert style, none of these settings has changed. Like I said, it's only an intermittent problem that happens while I am using another app or mail or Safari or whatever. Strangely enough, when I am using a music app (Pandora, etc.) that does not require me to actively use it (for example, I am listening to music but the lock screen is on, and when I unlock I'm just on my home screen... I do get text alerts. This is so weird and such a pain!

  • Is there a problem with copy paste using Ctrl+insert and Shift+insert

    This is a swing application.
    initially i was using java 1.3 and the copy paste using Ctrl+insert and Shift+insert was working
    then i migrated the same to java 1.5 and this functionality got messed up.

    Include the following in your initialization code, before you create any components:     InputMap im = (InputMap)UIDefaults.get("TextField.focusInputMap");
        im.put(KeyStroke.getKeyStroke("control INSERT"), DefaultEditorKit.copyAction);
        im.put(KeyStroke.getKeyStroke("shift INSERT"), DefaultEditorKit.pasteAction);
        im.put(KeyStroke.getKeyStroke("shift DELETE"), DefaultEditorKit.cutAction); You'll need to add the appropriate imports, too: import javax.swing.InputMap;
    import javax.swing.KeyStroke;
    import javax.swing.UIDefaults;
    import javax.swing.text.DefaultEditorKit; It seems they accidentally removed those bindings from JTextField under MetalLookAndFeel in JDK 1.5. They've been restored in JDK 1.6.

  • To measure and hold the peak value of voltage while measuriong using an accelerometer

    i would like to measure and hold the peak value of voltage while measuring using an accelerometer,when the voltage goes above certain range . also save highest 5 values.

    You could have a shift register on your acquisition loop that is initialized to hold an array of 5 values. Start with all 5 element holding something less than the expected normal input value.
    Now each time through the loop, test the new reading to see if it's greater than the minimum value in the 5-element array. If not just go on and repeat the loop.
    If the new reading is greater than the minimum value in the 5-element array, append the new reading to the array, sort it in decending order and drop the last element (the old minimum value).
    The array will hold the 5 greatest values and the max of the array will be the peak value.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Help, just got my iphone5 today and it is still not letting me text or phone or use the apps is there a maximum time i need to leave it for before it will be ready to use??

    got my iphone5 today and its not letting me text or phone or use the internet on it. is there an amount of time i am meant to leave it until i will be able to use this as a phone!

    What did your carrier say when you contacted them about the problem?

  • I am pulling my hair out! I am using adobe indesign and just want to make a text box 'autofit text' as I change fonts a lot and want the font to automatically re-size as I change it. help help help please - I have latest version of indesign - thanks

    I am pulling my hair out! I am using adobe indesign and just want to make a text box 'autofit text' as I change fonts a lot and want the font to automatically re-size as I change it.
    Is it not possible to create a text box, fill it with dynamic (data driven) text, but make the font size either scale up or down automatically, so that the entire text box is filled? This is a feature in PrintShop Mail Pro called COPY FIT. but no such feature in Indesign??
    help help help please - I have latest version of indesign - thanks, DJ

    lol... it seems to work, but I have another huge problem!
    Apparently .CSV files cannot contain page breaks in the data! The data I am trying to merge is a 'letter', with paragraphs, line breaks, etc.,
    But, after data merging, it ignores page breaks and only merges the first paragraph of each letter. (sigh)
    Solution? Hopefully, an EASY solution. lol as we have thousands of records.
    Is there a third party indesign plugin that will allow .xml, or .xls data merge import??
    Thx,
    DJ

  • HT201263 When my Ipod touch is in autolock I can only restart the device holding the sleep/wake button and home button at the same time for 10 seconds.  While in auto-lock it is using battery power and will do so until the battery is drained.  Whats wrong

    When my Ipod touch is in autolock I can only restart the device holding the sleep/wake button and home button at the same time for 10 seconds.  While in auto-lock it is using battery power and will do so until the battery is drained.  Whats wrong?

    - Try a reset. Nothing is lost:
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears
    - Connect the iPod to your computer and try to restore via iTunes. Try placing in Recovery mode if necessary to restore.
    - If you can't turn the iPod completely off, let the batter fully drain. After charging for at lerast anhour try again
    - If still not successful time for an appointment at the Genius Bar of an Apple store since it appears you have a hardware problem.

Maybe you are looking for

  • My iPhone 4s does not sync to iTunes 10.6.3.25

    I have an iPhone 4s iOS 5.1.1 and since I upgraded iTunes to 10.6.3.25 it goes through the sync process with no error messages, but does not sync playlists. Diagnostics says that sync is working fine. Tried reboot on iPhone. Reinstalled iTunes on PC.

  • How do I get Firefox to open my home page whenever I open a new tab?

    I have Google as my home page. Rather than opening a new tab and getting a blank page, I'd like to open a new tab and get Google coming up. I'm fairly certain that this was possible in old Firefox, and would like to know if it is still possible and i

  • SOUND ADVICE REQUIRED!

    Hi Folks, I've got an iMac G5 20" (have had it around 6 months). Just did a Software Update, and downloaded some widgets, and now the sound on all my games won't work. iMovie, iTunes, system noises etc all working fine but just no sound at all in the

  • HT204088 where is the payment history?

    How do I get payment history information?

  • Contract History Related to PO

    Hi How to verify the contract history with related to PO. Like PO history created based on contract Thanks Nick