Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-com-gists/f73ac440f53cf76f15662864f97fe34c to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/f73ac440f53cf76f15662864f97fe34c to your computer and use it in GitHub Desktop.
Built-in and custom text rendering, kerning, coordinates, text on images and vertical text.

Text Rendering Examples

Render TrueType text with a custom glyph outline painter using Aspose.Font for Java and Java 2D. The examples load Montserrat Bold and Lato Regular, position glyphs using their advances and pair kerning, and save black text on white and red text on yellow as PNG images.

Using the examples

Combine the rendering call, drawText, fontWidthToImageWidth and GlyphOutlinePainter fragments in one Java class. The painter implements IGlyphOutlinePainter and sends outline commands to GeneralPath; Graphics2D fills the paths on a 960 × 720 image.

Supply getDataDir() and getOutputDir() for your application. The sample paths use the sibling TTF directory containing montserrat-bold.ttf and LatoWeb-Regular.ttf; create the output directory before rendering. Lato Regular replaces the Lora Bold font used in the documentation.

The 300 DPI value controls coordinate scaling; it does not embed resolution metadata in the PNG. Required imports are shown in the Java source and include com.aspose.font, Java 2D, java.nio.file and javax.imageio.ImageIO.

Related Documentation

Related Resources

Requirements

  • JDK 8 or later and Maven for this example project
  • Aspose.Font for Java library
  • Java 2D and a PNG writer available through ImageIO; rendering supports headless operation
Aspose.Font for Java – Text Rendering Examples
// Learn more: https://docs.aspose.com/font/java/text-rendering-truetype-font/
private static void drawText(String text, IFont font, double fontSize,
Paint backgroundBrush, Paint textBrush, String outputFile) throws IOException {
GlyphId[] glyphIds = new GlyphId[text.length()];
for (int i = 0; i < text.length(); i++) {
glyphIds[i] = font.getEncoding().decodeToGid(text.charAt(i));
}
double dpi = 300;
double resolutionCorrection = dpi / 72;
BufferedImage outputBitmap = new BufferedImage(960, 720, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = outputBitmap.createGraphics();
try {
graphics.setPaint(backgroundBrush);
graphics.fillRect(0, 0, outputBitmap.getWidth(), outputBitmap.getHeight());
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
GlyphId previousGlyphId = null;
double glyphXCoordinate = 0;
double glyphYCoordinate = fontSize * resolutionCorrection;
for (GlyphId glyphId : glyphIds) {
if (glyphId == null) {
continue;
}
Glyph glyph = font.getGlyphAccessor().getGlyphById(glyphId);
if (glyph == null) {
continue;
}
if (previousGlyphId != null) {
double kerning = font.getMetrics().getKerningValue(previousGlyphId, glyphId)
/ glyph.getSourceResolution() * fontSize * resolutionCorrection;
double advance = fontWidthToImageWidth(font.getMetrics().getGlyphWidth(previousGlyphId),
glyph.getSourceResolution(), fontSize, dpi);
glyphXCoordinate += kerning + advance;
}
GeneralPath path = new GeneralPath();
IGlyphRenderer renderer = new GlyphOutlineRenderer(new GlyphOutlinePainter(path));
TransformationMatrix matrix = new TransformationMatrix(new double[] {
fontSize * resolutionCorrection, 0, 0, -fontSize * resolutionCorrection,
glyphXCoordinate, glyphYCoordinate
});
renderer.renderGlyph(font, glyphId, matrix);
path.setWindingRule(GeneralPath.WIND_NON_ZERO);
graphics.setPaint(textBrush);
graphics.fill(path);
previousGlyphId = glyphId;
}
} finally {
graphics.dispose();
}
if (!ImageIO.write(outputBitmap, "png", new File(outputFile))) {
throw new IOException("No PNG writer is available.");
}
}
// Learn more: https://docs.aspose.com/font/java/text-rendering-truetype-font/
private static double fontWidthToImageWidth(double width, int fontSourceResolution,
double fontSize, double dpi) {
return width / fontSourceResolution * fontSize * (dpi / 72);
}
// Learn more: https://docs.aspose.com/font/java/text-rendering-truetype-font/
private static final class GlyphOutlinePainter implements IGlyphOutlinePainter {
private final GeneralPath path;
private GlyphOutlinePainter(GeneralPath path) {
this.path = path;
}
@Override
public void moveTo(MoveTo moveTo) {
path.moveTo(moveTo.getX(), moveTo.getY());
}
@Override
public void lineTo(LineTo lineTo) {
path.lineTo(lineTo.getX(), lineTo.getY());
}
@Override
public void curveTo(CurveTo curveTo) {
path.curveTo(curveTo.getX1(), curveTo.getY1(), curveTo.getX2(), curveTo.getY2(),
curveTo.getX3(), curveTo.getY3());
}
@Override
public void closePath() {
path.closePath();
}
}
// Learn more: https://docs.aspose.com/font/java/text-rendering-truetype-font/
String firstFontPath = Paths.get(getDataDir(), "..", "TTF", "montserrat-bold.ttf")
.normalize().toString();
String secondFontPath = Paths.get(getDataDir(), "..", "TTF", "LatoWeb-Regular.ttf")
.normalize().toString();
TtfFont firstFont = (TtfFont) Font.open(new FontDefinition(FontType.TTF,
new FontFileDefinition("ttf", new FileSystemStreamSource(firstFontPath))));
TtfFont secondFont = (TtfFont) Font.open(new FontDefinition(FontType.TTF,
new FontFileDefinition("ttf", new FileSystemStreamSource(secondFontPath))));
String firstOutput = Paths.get(getOutputDir(), "hello1_montserrat_out.png").toString();
String secondOutput = Paths.get(getOutputDir(), "hello2_lato_out.png").toString();
drawText("Hello world", firstFont, 14, Color.WHITE, Color.BLACK, firstOutput);
drawText("Hello world", secondFont, 14, Color.YELLOW, Color.RED, secondOutput);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment