Text

One of the keys to understanding Java 2D text rendering is to realize that in most ways text can be treated as a shape. As such, most of the methods used on shape primitives can be used on text primitives. However, some special properties of graphics-based text should be considered.

Before diving into these special properties, it is necessary to consider some terminology. The different terms used to describe text, layout, and style largely reflect the different ways primitives are grouped to lay out text.

The overall goal of text layout is to artistically represent symbols (known as characters) that have meaning in a particular language. Each character is represented by a set of shape primitives called glyphs. Technically, glyphs are made up of little bitmapped images. Often, but not always, a single glyph represents a single character.

To render a character, then, it is necessary to assemble a set of glyphs. This is accomplished through a lookup (mapping) table that specifies the glyphs to use for each particular character. A current standard, and the one used by Java, is Unicode.

A font is simply the collection of glyphs needed to make a set of characters with a particular style and size. The collection of glyphs that make up the font known as Helvetica 10 point, for example, will be different from the set of glyphs representing Times New Roman 10 point because of the subtle differences in the way the curves arch, the lines are terminated, and so on. An interesting exercise is to zoom in closely on text with a variety of fonts using any drawing program. It is easy to see the glyphs and subtle differences among the different fonts.

Most of the classes and interfaces discussed in this section are part of the java.awt.Font package.

Getting a List of Available Fonts

The first point of divergence concerning shapes and fonts is that each environment doesn't have the same resident fonts. Java has a very useful method for determining the fonts recognized by the system. The GraphicsEnvironment object's getAvailableFontFamilyNames() method returns an array of strings containing the names of the available fonts on the system. The following code can be put in a Java program to print a list of fonts available. Likewise, the fonts can be added to a Collection object (that is, vector or hash table) for use in user interface selection.

GraphicsEnvironment ge =
    GraphicsEnvironment.getLocalGraphicsEnvironment();

    String availablefonts[] =
    ge.getAvailableFontFamilyNames();

    for ( int i = 1; i < availablefonts.length; i++ ) {
         System.out.println(envfonts[i]);
    }

Laying Out Text

Before going too deeply into Java 2D's text rendering methods, you should know that most applications can get by with a very simple model of getting an instance of a font, setting the Graphics2D context for that font with the setFont() method, and using the Graphics2D rendering method drawString() to render a string. This is the clear way to go for basic tasks such as labeling the axis of a plot and placing short strings of text on the screen.

That said, Java 2D has some pretty advanced text rendering capabilities, most of which can be realized with the TextLayout class (discussed next). The following introduction will hardly scratch the surface of the different kinds of text processing that are possible with Java 2D, but should provide enough of an introduction so that you can continue. We will focus on a few classes, primarily the TextLayout and AttributedString classes.

Introduction to the TextLayout Class

When producing even the most rudimentary text layout, it is often necessary to combine strings in different styles and control the flow of the text as in a paragraph layout. TextLayout is the essential class for laying sections of text. It is a graphical representation of character data that allows for most of the advanced text capabilities of Java 2D. Table 3.5 lists some of these capabilities.

Table 3.5. Text Layout Operations Supported in Java 2D
Layout Operation Description
International Support Classes to handle many challenges in producing international text such as right-to-left language. Conforms to Unicode97 standard.
Editing Editing, carets, cursor positioning, highlighting
Rendering Justification, text metrics
Paragraph Layout Use in conjunction with LineBreakMeasurer

After the TextLayout object is instantiated, it can be rendered either through its own draw() method or through Graphics2D's drawString() method. The following code snippet illustrates the basic use of TextLayout:

FontRenderContext frc = g2d.getFontRenderContext();  //contains measurement info
Font f = new Font("Helvetica",Font.BOLD, 24);
String s = new String("Simple test string");
TextLayout textlayout = new TextLayout(s, f, frc);
Textlayout.draw(g2d, height, width);   //use TextLayout's draw method

There are several things to notice in the previous code snippet. First, although we created a TextLayout object, we didn't do anything very special with it. In fact, this snippet achieves the same result that we would have realized with the drawString() method. The use of TextLayout with longer strings is left as an exercise for you. Generally, it is useful to read in longer strings from an external file.

Second, notice that it is necessary to create an instance of FontRenderContext to pass to the TextLayout constructor. The FontRenderContext object contains the basic information important for measuring text (also known as font metrics), including a reference to the mathematical transform necessary to convert points to pixels as well as information about specific rendering attributes that might have been set as such. Rendering attributes include whether antialiasing has been set or fractional metrics are in use. Although all the TextLayout constructors require the FontRenderContext object to be passed, it isn't necessary to worry too much about FontRenderContext for most applications in general.

A final point about the previous code snippet is that once instantiated, the TextLayout object is immutable. Therefore, any changes to the text layout (such as changing the string) during program operation will require the creation of a new TextLayout object.

Generating an Attributed String for TextLayout

As stated previously, we haven't done anything special with our TextLayout object. Because it is immutable once it is created anyway, we are pretty limited in our text layout possibilities. The key to using the immutable TextLayout object is in generating an AttributedCharacterIterator object to pass to the TextLayout constructor (or, alternatively, the Graphics2D drawString() method).

The AttributedCharacterIterator is used by Graphics2D and TextLayout when rendering styled text to walk through the text to be rendered. This is completely analogous to the PathIterator object for moving around the boundary of a shape that was demonstrated previously.

A common source of confusion arises because the programmer doesn't specify the details of pairing characters and their attributes. Instead, the pairings are specified in an AttributedString object. This step accounts for the majority of the work in laying out the text. The AttributedCharacterIterator is then instantiated with the AttributedString's getIterator() method.

The following code represents a prototypical example of setting the attributes (colors, sizes, and fonts) of individual characters in a line of text. Step 1 involves instantiating the AttributedString object without setting the attributes. We will set the attributes short. Although this is probably the easiest way to proceed, other constructors of AttributedString will allow you to set the attributes in the constructor. Regardless, let's instantiate the object and add some attributes:

//step one; create the AttributedString object
String text = new String("abcdefghijklmnopqrstuvwxyz");
AttributedString attText = new AttributedString(text);

//step two;add some attributes
attText.addAttribute(TextAttribute.FOREGROUND, Color.black);  //default
attText.addAttribute(TextAttribute.FAMILY, "helvetica"); //helvetica

//step three; change attribute of the third character

for (int i;i<25;i++) {
     attText.addAttribute(TextAttribute.SIZE, (float) 2*i, i, i+1 );
}

Remember that the TextAttribute.FONT attribute supercedes all other font attributes (for example, the TextureAttribute.FAMILY attribute set previously).

Another caveat is that all graphical information returned from a TextLayout object's methods is relative to the origin of the TextLayout, which is the intersection of the TextLayout object's baseline with its left edge. Also, coordinates passed into a TextLayout object's methods are assumed to be relative to the TextLayout object's origin.

Dozens of attributes can be added. The full list is located at http://java.sun.com/j2se/1.3/docs/api/java/awt/font/TextAttribute.html.

Formatting Paragraph Text

The code from the preceding section represents one way to create a TextLayout object and is sufficient for single lines of text. A second class, however, called LineBreakMeasurer, also creates a TextLayout object but further provides methods to control the line breaks to form blocks of text. LineBreakMeasurer is intended for use in laying out paragraphs.

The strategy implemented by LineBreakMeasurer is simply to place as many words on each line as will fit. If a word won't fit in its entirety on a given line, a break is placed before it and it is shifted to the next line. Strategies that use hyphenation or minimize the differences in line length within paragraphs require low-level calls and aren't handled easily with LineBreakMeasurer.

In order to break a paragraph of text into lines, it is necessary to construct a LineBreakMeasurer object for the entire paragraph. Separate segments of the text are obtained using the nextLayout() method, which returns a TextLayout object that fits within the specified width for each line (called the wrapping width). When the nextLayout() method reaches the end of the text, it returns Null to indicate that no more segments are available.

Inserting Shapes and Images into Text

It is also possible to embed shapes and even images into a line of text. This is accomplished by adding the TextureAttribute.CHAR_REPLACEMENT attribute with the desired replacement object. For shapes and images, the replacement object needs to be an object of type ShapeGraphicsAttribute or ImageGraphicsAttribute, respectively.

Building a Custom Font

Another somewhat common task is the creation of a custom font based on an existing font. This can be accomplished by passing an existing font name with the desired size and style to the constructor of the Font class. It is also possible to use the deriveFont() method:

Font sourceFont = new Font("Helvetica", Font.ITALICS, 12);
Font derivedFont = fontSource.deriveFont(Font.BOLD, 12);

Of course, there are much more interesting things you would want to do with a custom font. The deriveFont() method has a number of constructors, including one for using a custom attribute mapping and another for applying affine transforms to fonts. (For information on the AffineTransform class, see the later section “Coordinate Space Transformations.”)

Text Hit Testing

The TextLayout class greatly simplifies the task of hit testing in text with three methods, getNextRightHit(), getNextLeftHit(), and hitTestChar(), that each return an instance of TextHitInfo. A TextHitInfo object contains information about the character position within a text model as well as its bias (whether the position is to the right or to the left of the character). You should bear in mind that the offsets contained in TextHitInfo objects are specified relative to the start of the TextLayout object and not to the text used to create the TextLayout.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset