Home Java Example Java Swing Graphics2D Draw text like a curve
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Draw text like a curve

Advertisement
To draw the text, we have used the Font class which represents the font to render the text.

Draw text like a curve

     

This section illustrates you how to draw the text like a curve.

To draw the text, we have used the Font class which represents the font to render the text. The method getFontRenderContext() of class Graphics2D get the rendering context of the font specified. The method translate(30,60) translates the origin.

The class GlyphVector represents the collection of glyphs. A glyph is a shape which render a character or a sequence of characters. The method createGlyphVector() provides one-to-one mapping of characters to glyphs. The method getNumGlyphs() returns the number of glyphs in the GlyphVector. The method getGlyphPosition(p) returns the position of the specified glyph.

The class AffineTransform provides the rotation property. The method rotate(angle) rotates the text like a curve. The method getGlyphOutline() of class GlyphVector returns the shape of the specified glyph. 

Following code returns a new shape after it has been transformed by the AffineTransform:

affineTransform.createTransformedShape(shape1);

Here is the code of ShowTextCreateCurve.java

import java.awt.*;
import javax.swing.*;
import java.awt.font.*;
import java.awt.geom.*;

public class ShowTextCreateCurve extends JPanel {
  public void paint(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;

  Font font = new Font("Arial Narrow", Font.ITALIC, 20);
  FontRenderContext fontRenderContext = g2d.getFontRenderContext();
  g2d.translate(3060);

  GlyphVector glyphVector = font.createGlyphVector(fontRenderContext,
  "Java is a platform independent language."
);
  int len = glyphVector.getNumGlyphs();
  for (int p = 0; p < len; p++) {
  Point2D point = glyphVector.getGlyphPosition(p);
  double angle = (double) p / (double) (len - 1) * Math.PI / 2.5;
  AffineTransform affineTransform = AffineTransform.getTranslateInstance(
  point.getX(),point.getY());

  affineTransform.rotate(angle);
  Shape shape1 = glyphVector.getGlyphOutline(p);
  Shape shape2 = affineTransform.createTransformedShape(shape1);
  g2d.setPaint(Color.red);
  g2d.fill(shape2);
  }
  }
  public static void main(String[] args) {
  JFrame frame = new JFrame("Show Rolling Text");
  frame.getContentPane().add(new ShowTextCreateCurve());
  frame.setSize(550380);
  frame.show();
  }
}

Output will be displayed as:

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 16, 2008

Ask Questions?    Discuss: Draw text like a curve  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com