Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020