renderizar texto usando fuente en Java

En el artículo anterior, vio cómo cargar fuentes CFF, TrueType y Type1 mediante programación usando Java. Hoy, discutiremos otra característica interesante de nuestra API de manipulación de fuentes de Java: renderizar texto usando fuentes. Al final de este artículo, podrá representar texto utilizando fuentes TrueType y Type1 desde sus aplicaciones Java. Así que empecemos.

API de manipulación de fuentes Java

Aspose.Font for Java le brinda las funciones de cargar y guardar las fuentes, así como obtener las métricas de los tipos de fuentes populares, incluidos CFF, TrueType, OpenType y Type1. Además, la API le permite representar el texto utilizando las fuentes TrueType o Type1 proporcionadas. Puede instalar la API usando las configuraciones de Maven o descargar el JAR de la API.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-font</artifactId>
    <version>20.10</version>
</dependency>

Implementar el método de representación de texto

Para representar el texto, Aspose.Font for Java requiere que implemente el método drawText() que dibujará el texto proporcionado. La siguiente es la definición completa del método drawText().

// Para obtener ejemplos completos y archivos de datos, vaya a https://github.com/aspose-font/Aspose.Font-for-Java
static void drawText(String text, IFont font, double fontSize,
           Paint backgroundBrush, Paint textBrush, String outFile) throws Exception
{
    //Obtenga identificadores de glifos para cada símbolo en la línea de texto
    GlyphId[] gids = new GlyphId[text.length()];
    for (int i = 0; i < text.length(); i++)
        gids[i] = font.getEncoding().decodeToGid(text.charAt(i));
    // establecer configuraciones de dibujo comunes
    double dpi = 300;
	
    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // preparar Bitmap de salida
    BufferedImage outBitmap = new BufferedImage(960, 720, BufferedImage.TYPE_INT_BGR);
    //outBitmap.getRaster().SetResolution((float)dpi, (float)dpi);
    java.awt.Graphics2D outGraphics = (java.awt.Graphics2D) outBitmap.getGraphics();
    outGraphics.setPaint(backgroundBrush);
    outGraphics.fillRect(0, 0, outBitmap.getWidth(), outBitmap.getHeight());
    outGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    //declarar variables de coordenadas y gid anterior
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //bucle que pinta cada glifo en gids
    for (GlyphId gid : gids)
    {
        // si la fuente contiene el gid
        if (gid != null)
        {
            Glyph glyph = font.getGlyphAccessor().getGlyphById(gid);
            if (glyph == null)
                continue;
	
            // ruta que acepta instrucciones de dibujo
            GeneralPath path = new GeneralPath();
	
            // Crear implementación de IGlyphOutlinePainter
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);
	
            // Crear el renderizador
            IGlyphRenderer renderer = new GlyphOutlineRenderer(outlinePainter);
	
            // obtener propiedades de glifo comunes
            double kerning = 0;
	
            // obtener valor de interletraje
            if (previousGid != null)
            {
                kerning = (font.getMetrics().getKerningValue(previousGid, gid) /
                           glyph.getSourceResolution()) * fontSize * resolutionCorrection;
                kerning += fontWidthToImageWdith(font.getMetrics().getGlyphWidth(previousGid),
                        glyph.getSourceResolution(), fontSize, 300);
            }
	
            // posicionamiento de glifo: aumenta la coordenada X del glifo según la distancia de interletraje
            glyphXCoordinate += kerning;
	
            // Matriz de colocación de glifos
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // negativo debido al sistema de coordenadas de Bitmap que comienza desde arriba
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });
	
            // representar el glifo actual
            renderer.renderGlyph(font, gid, glyphMatrix);
            // llenar el camino
            path.setWindingRule(GeneralPath.WIND_NON_ZERO);
            outGraphics.setPaint(textBrush);
            outGraphics.fill(path);
        }
        //establezca el gid actual como anterior para obtener el interletraje correcto para el siguiente glifo
        previousGid = gid;
    }
    //Guardar resultados
    ImageIO.write(outBitmap, "jpg", new File(outFile));
}

El siguiente es un método de utilidad que se utiliza para calcular el ancho de glifo para el sistema de coordenadas de Bitmap.

// Para obtener ejemplos completos y archivos de datos, vaya a https://github.com/aspose-font/Aspose.Font-for-Java
static double fontWidthToImageWidth(double width, int fontSourceResulution, double fontSize, double dpi)
{
    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    return (width / fontSourceResulution) * fontSize * resolutionCorrection;
}

Pasos para renderizar texto con fuente en Java

Los siguientes son los pasos para representar un texto específico como un archivo de imagen utilizando el método darwText() mencionado anteriormente.

  • Cargue la fuente usando la clase FontDefinition.
  • Acceda a la fuente usando la clase como Type1Font o TtfFont.
  • Llame al método drawText() proporcionando los detalles en forma de sus parámetros.

Renderizar texto con fuente TrueType usando Java

El siguiente ejemplo de código muestra cómo usar el método drawText() para representar texto usando una fuente TrueType. Los resultados de la renderización se generarán como una imagen JPEG.

// Para obtener ejemplos completos y archivos de datos, vaya a https://github.com/aspose-font/Aspose.Font-for-Java
String fileName1 = Utils.getDataDir() + "Montserrat-Bold.ttf"; //Font file name with full path
      FontDefinition fd1 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName1)));
      TtfFont font1 = (TtfFont) Font.open(fd1);
      
      String fileName2 = Utils.getDataDir() + "Lora-Bold.ttf"; //Font file name with full path
      FontDefinition fd2 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName2)));
      TtfFont font2 = (TtfFont) Font.open(fd2);
      
      try {
       drawText("Hello world", font1, 14, java.awt.Color.WHITE, java.awt.Color.BLACK, Utils.getDataDir() + "hello1_montserrat_out.jpg");
       drawText("Hello world", font2, 14, java.awt.Color.YELLOW, java.awt.Color.RED, Utils.getDataDir() + "hello2_lora_out.jpg");
      } catch (Exception ex) {
      	ex.printStackTrace();
      }

Renderizar texto usando fuentes Type1 en Java

El siguiente ejemplo de código muestra cómo representar texto en una imagen JPEG con una fuente Type1 usando Java.

// Para obtener ejemplos completos y archivos de datos, vaya a https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "courier.pfb"; //Font file name with full path

FontDefinition fd = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
      Type1Font font = (Type1Font) Font.open(fd);
      
      try {
       drawText("Hello world", font, 14, java.awt.Color.WHITE, java.awt.Color.BLACK, Utils.getDataDir() + "hello1_type1_out.jpg");
       drawText("Hello world", font, 14, java.awt.Color.YELLOW, java.awt.Color.RED, Utils.getDataDir() + "hello2_type1_out.jpg");
      } catch (Exception ex) {
      	ex.printStackTrace();
      }

Conclusión

En este artículo, ha visto cómo representar el texto como imágenes JPEG utilizando la fuente TrueType o Type1 desde las aplicaciones Java. Para obtener más información sobre la API de manipulación de fuentes Java, puede visitar la documentación y evaluar las características de la API usando ejemplos de código fuente.