Text Rendering using TrueType Font | Java
Contents
[
Hide
Show
]Rendering Text
In order to render text, the Rendering subsystem requires the implementation of Aspose.Font.Rendering.IGlyphOutlinePainter interface to draw glyph. This can be achieved using the following steps.
- Create method
DrawText()
which draws specified text into System.Drawing.Bitmap object and saves resultant bitmap on Disc. This will include the following steps:
- Iterate all symbols in text string.
- Get glyph identifier for every processed symbol - gid.
- Create object of type GlyphOutlinePainter which is required by rendering subsystem to draw current glyph.
- Create object of type Aspose.Font.Renderers.GlyphOutlineRenderer, and pass just created object of type GlyphOutlinePainter into constructor for GlyphOutlineRenderer. This object GlyphOutlineRenderer intended to render specified glyph.
- Render current processed glyph using method GlyphOutlineRenderer.RenderGlyph(). Aspose.Fonts.Matrix object is used to specify glyph coordinates. Glyph to render is specified by gid parameter.
Auxillary steps for this strategy
- Glyph coordinate for ‘Y’ axis is constant for this code snippet.
- Glyph coordinate for ‘X’ axis is calculated for every processed glyph.
- Both ‘X’ and ‘Y’ coordinates are passed into object Aspose.Fonts.Matrix which is used by GlyphOutlineRenderer to draw glyph.
- Distance between just processed and previous glyphs is calculated on every iteration step. This distance affects every glyph ‘X’ coordinate.
- Object of type GlyphOutlinePainter draws glyph with the help of GlyphOutlinePainter not into Bitmap directly, but into object GraphicsPath, which was passed into constructor for GlyphOutlinePainter, so we use object of type System.Drawing.Graphics to draw GraphicsPath into Bitmap.
- Method FontWidthToImageWith() which calculates glyph width for bitmap coordinate system.
Implementation of DrawText method is as shown below.
1// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
2static void drawText(String text, IFont font, double fontSize,
3 Paint backgroundBrush, Paint textBrush, String outFile) throws Exception
4{
5 //Get glyph identifiers for every symbol in text line
6 GlyphId[] gids = new GlyphId[text.length()];
7 for (int i = 0; i < text.length(); i++)
8 gids[i] = font.getEncoding().decodeToGid(text.charAt(i));
9 // set common drawing settings
10 double dpi = 300;
11
12 double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
13 // prepare output bitmap
14 BufferedImage outBitmap = new BufferedImage(960, 720, BufferedImage.TYPE_INT_BGR);
15 //outBitmap.getRaster().SetResolution((float)dpi, (float)dpi);
16 java.awt.Graphics2D outGraphics = (java.awt.Graphics2D) outBitmap.getGraphics();
17 outGraphics.setPaint(backgroundBrush);
18 outGraphics.fillRect(0, 0, outBitmap.getWidth(), outBitmap.getHeight());
19 outGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
20 //declare coordinate variables and previous gid
21 GlyphId previousGid = null;
22 double glyphXCoordinate = 0;
23 double glyphYCoordinate = fontSize * resolutionCorrection;
24 //loop which paints every glyph in gids
25 for (GlyphId gid : gids)
26 {
27 // if the font contains the gid
28 if (gid != null)
29 {
30 Glyph glyph = font.getGlyphAccessor().getGlyphById(gid);
31 if (glyph == null)
32 continue;
33
34 // path that accepts drawing instructions
35 GeneralPath path = new GeneralPath();
36
37 // Create IGlyphOutlinePainter implementation
38 GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);
39
40 // Create the renderer
41 IGlyphRenderer renderer = new GlyphOutlineRenderer(outlinePainter);
42
43 // get common glyph properties
44 double kerning = 0;
45
46 // get kerning value
47 if (previousGid != null)
48 {
49 kerning = (font.getMetrics().getKerningValue(previousGid, gid) /
50 glyph.getSourceResolution()) * fontSize * resolutionCorrection;
51 kerning += fontWidthToImageWdith(font.getMetrics().getGlyphWidth(previousGid),
52 glyph.getSourceResolution(), fontSize, 300);
53 }
54
55 // glyph positioning - increase glyph X coordinate according to kerning distance
56 glyphXCoordinate += kerning;
57
58 // Glyph placement matrix
59 TransformationMatrix glyphMatrix =
60 new TransformationMatrix(
61 new double[]
62 {
63 fontSize*resolutionCorrection,
64 0,
65 0,
66 // negative because of bitmap coordinate system begins from the top
67 - fontSize*resolutionCorrection,
68 glyphXCoordinate,
69 glyphYCoordinate
70 });
71
72 // render current glyph
73 renderer.renderGlyph(font, gid, glyphMatrix);
74 // fill the path
75 path.setWindingRule(GeneralPath.WIND_NON_ZERO);
76 outGraphics.setPaint(textBrush);
77 outGraphics.fill(path);
78 }
79 //set current gid as previous to get correct kerning for next glyph
80 previousGid = gid;
81 }
82 //Save results
83 ImageIO.write(outBitmap, "jpg", new File(outFile));
84}
- create utility method to calculate font width to image width as shown in the code sample below
1// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
2static double fontWidthToImageWidth(double width, int fontSourceResulution, double fontSize, double dpi)
3{
4 double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
5 return (width / fontSourceResulution) * fontSize * resolutionCorrection;
6}
Calling the Rendering Text functionality
To use the above implementations, the following sample code can be executed from the Main method of a console based application.
1// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
2String fileName1 = Utils.getDataDir() + "Montserrat-Bold.ttf"; //Font file name with full path
3 FontDefinition fd1 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName1)));
4 TtfFont font1 = (TtfFont) Font.open(fd1);
5
6 String fileName2 = Utils.getDataDir() + "Lora-Bold.ttf"; //Font file name with full path
7 FontDefinition fd2 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName2)));
8 TtfFont font2 = (TtfFont) Font.open(fd2);
9
10 try {
11 drawText("Hello world", font1, 14, java.awt.Color.WHITE, java.awt.Color.BLACK, Utils.getDataDir() + "hello1_montserrat_out.jpg");
12 drawText("Hello world", font2, 14, java.awt.Color.YELLOW, java.awt.Color.RED, Utils.getDataDir() + "hello2_lora_out.jpg");
13 } catch (Exception ex) {
14 ex.printStackTrace();
15 }