James Williams
LinkedInMastodonGithub

Displaying Text with PlayN

Tags: Gaming

If you have ever added text to a HTML5 Canvas image, you already know the process to create text in PlayN.

  1. Declare/Retrieve the font
  2. Add attributes such as font weight, color, and styling.
  3. Layout text.
  4. Draw it to a canvas buffer.

For my video poker game, I used a utility to store the functions to create text. The createMessageText function does the bulk of the work instantiating a Font object and determining the layout based on the given attributes. It then sends the layout and font color to the createTextLayer function. It creates an ImageLayer with the drawn text inside it. In the code below, I used fillText to create solid text but you could alternatively use strokeText to draw only the outlines or some combination of the two.

package com.html5gamebook.core;

import playn.core.*;
import static playn.core.PlayN.*;


class Util {
  static Layer createMessageText(String text, int fontSize, Integer fontColor) {
      Font font = graphics().createFont("Sans serif", Font.Style.PLAIN, fontSize);
      TextLayout layout = graphics().layoutText(
        text, new TextFormat().withFont(font).withWrapWidth(200));
      Layer textLayer = createTextLayer(layout, fontColor);
      return textLayer;
    }

  static Layer createTextLayer(TextLayout layout, Integer fontColor) {
      CanvasImage image = graphics().createImage((int)Math.ceil(layout.width()),
                                                 (int)Math.ceil(layout.height()));
      if (fontColor != null) image.canvas().setFillColor(fontColor);
      image.canvas().fillText(layout, 0, 0);
      return graphics().createImageLayer(image);
    }

}

If you aren't using a font that is universally available, you might have to register the font programmatically with that platform.

Note: You can also display text with the UI library TriplePlay.