Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate text with Graphics2D in Java?

Tags:

I want to rotate text on a JPanel using Graphics2D..

My code is this:

double paso=d.width/numeroBarras;         double alto=datos[i].valor;         Font fBarras=new Font("Serif", Font.PLAIN, 15);         g2.setFont(fBarras);         Rectangle2D barra=new Rectangle2D.Double(x,d.height-alto,paso,alto);         //g2.fill(barra);         x+=paso;         g2.draw(barra);         g2.rotate(-Math.PI/2);         g2.setColor(Color.BLACK);         g2.drawString(datos[i].titulo,(float)alto,(float)paso) 

This method must draw a rectangle and a text over the rectangle, but when i run this method all the graphic is rotated and i just want rotate the text ..

Thanks :)

like image 588
Rafael Carrillo Avatar asked Apr 10 '12 06:04

Rafael Carrillo


People also ask

How do you rotate text in Java?

Java AWT Programming Project By default, JLabel can display a text in the horizontal position and we can rotate a JLabel text by implementing the rotate() method of Graphics2D class inside the paintComponent().

How do you rotate a pixel in Java?

The simplest way to rotate an image in Java is to use the AffineTransformOp class. You can load an image into Java as a BufferedImage and then apply the rotate operation to generate a new BufferedImage. You can use Java's ImageIO or a third-party image library such as JDeli to load and save the image.


2 Answers

This method will rotate the text and will render all other shapes the same.

Graphics2D g2 = (Graphics2D) g; Font font = new Font(null, Font.PLAIN, 10);     AffineTransform affineTransform = new AffineTransform(); affineTransform.rotate(Math.toRadians(45), 0, 0); Font rotatedFont = font.deriveFont(affineTransform); g2.setFont(rotatedFont); g2.drawString("A String",0,0); g2.dispose(); 
like image 99
Titus Avatar answered Sep 19 '22 12:09

Titus


The method Graphics2D.rotate applies transform to all subsequent rendering operations. You can preserve a copy of transform (with getTransform()) before applying rotation, and then restore the original.

g2.draw(barra); AffineTransform orig = g2.getTransform(); g2.rotate(-Math.PI/2); g2.setColor(Color.BLACK); g2.drawString(datos[i].titulo,(float)alto,(float)paso); g2.setTransform(orig); 
like image 23
Mersenne Avatar answered Sep 16 '22 12:09

Mersenne