Java에서 글꼴을 사용하여 텍스트 렌더링

이전 기사에서 Java를 사용하여 프로그래밍 방식으로 CFF, TrueTypeType1 글꼴을 로드하는 방법을 살펴보았습니다. 오늘 우리는 Java 글꼴 조작 API의 또 다른 흥미로운 기능인 글꼴을 사용하여 텍스트를 렌더링하는 것에 대해 논의할 것입니다. 이 기사가 끝나면 Java 응용 프로그램 내에서 TrueType 및 Type1 글꼴을 사용하여 텍스트를 렌더링할 수 있습니다. 시작하겠습니다.

자바 글꼴 조작 API

Aspose.Font for Java는 글꼴 로드 및 저장 기능과 CFF, TrueType, OpenType, Type1을 비롯한 인기 있는 글꼴 유형의 메트릭을 가져오는 기능을 제공합니다. 또한 API를 사용하면 제공된 TrueType 또는 Type1 글꼴을 사용하여 텍스트를 렌더링할 수 있습니다. Maven 구성을 사용하여 API를 설치하거나 API의 JAR을 다운로드할 수 있습니다.

<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>

텍스트 렌더링 방법 구현

텍스트를 렌더링하려면 Java용 Aspose.Font에서 제공된 텍스트를 그릴 drawText() 메서드를 구현해야 합니다. 다음은 drawText() 메서드의 전체 정의입니다.

// 전체 예제 및 데이터 파일을 보려면 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
{
    //텍스트 줄의 모든 기호에 대한 글리프 식별자 가져오기
    GlyphId[] gids = new GlyphId[text.length()];
    for (int i = 0; i < text.length(); i++)
        gids[i] = font.getEncoding().decodeToGid(text.charAt(i));
    // 공통 도면 설정 지정
    double dpi = 300;
	
    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // 출력 비트맵 준비
    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);
    //좌표 변수 및 이전 gid 선언
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //gid의 모든 글리프를 그리는 루프
    for (GlyphId gid : gids)
    {
        // 글꼴에 gid가 포함된 경우
        if (gid != null)
        {
            Glyph glyph = font.getGlyphAccessor().getGlyphById(gid);
            if (glyph == null)
                continue;
	
            // 그리기 지시를 받아들이는 경로
            GeneralPath path = new GeneralPath();
	
            // IGlyphOutlinePainter 구현 생성
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);
	
            // 렌더러 만들기
            IGlyphRenderer renderer = new GlyphOutlineRenderer(outlinePainter);
	
            // 공통 글리프 속성 얻기
            double kerning = 0;
	
            // 커닝 값 얻기
            if (previousGid != null)
            {
                kerning = (font.getMetrics().getKerningValue(previousGid, gid) /
                           glyph.getSourceResolution()) * fontSize * resolutionCorrection;
                kerning += fontWidthToImageWdith(font.getMetrics().getGlyphWidth(previousGid),
                        glyph.getSourceResolution(), fontSize, 300);
            }
	
            // 글리프 포지셔닝 - 커닝 거리에 따라 글리프 X 좌표 증가
            glyphXCoordinate += kerning;
	
            // 글리프 배치 매트릭스
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // 비트맵 좌표계가 맨 위에서 시작하기 때문에 음수
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });
	
            // 현재 글리프 렌더링
            renderer.renderGlyph(font, gid, glyphMatrix);
            // 길을 채우다
            path.setWindingRule(GeneralPath.WIND_NON_ZERO);
            outGraphics.setPaint(textBrush);
            outGraphics.fill(path);
        }
        //다음 글리프에 대한 올바른 커닝을 얻으려면 현재 gid를 이전으로 설정하십시오.
        previousGid = gid;
    }
    //결과 저장
    ImageIO.write(outBitmap, "jpg", new File(outFile));
}

다음은 비트맵 좌표계에 대한 글리프 너비를 계산하는 데 사용되는 유틸리티 방법입니다.

// 전체 예제 및 데이터 파일을 보려면 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;
}

Java에서 글꼴로 텍스트를 렌더링하는 단계

다음은 위에서 언급한 darwText() 메서드를 사용하여 지정된 텍스트를 이미지 파일로 렌더링하는 단계입니다.

  • FontDefinition 클래스를 사용하여 글꼴을 로드합니다.
  • Type1Font 또는 TtfFont과 같은 클래스를 사용하여 글꼴에 액세스합니다.
  • 매개변수 형식으로 세부사항을 제공하여 drawText() 메소드를 호출하십시오.

Java를 사용하여 TrueType 글꼴로 텍스트 렌더링

다음 코드 샘플은 drawText() 메서드를 사용하여 TrueType 글꼴을 사용하여 텍스트를 렌더링하는 방법을 보여줍니다. 렌더링 결과는 JPEG 이미지로 생성됩니다.

// 전체 예제 및 데이터 파일을 보려면 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();
      }

Java에서 Type1 글꼴을 사용하여 텍스트 렌더링

다음 코드 샘플은 Java를 사용하여 Type1 글꼴로 텍스트를 JPEG 이미지로 렌더링하는 방법을 보여줍니다.

// 전체 예제 및 데이터 파일을 보려면 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();
      }

결론

이 기사에서는 Java 애플리케이션 내에서 TrueType 또는 Type1 글꼴을 사용하여 텍스트를 JPEG 이미지로 렌더링하는 방법을 살펴보았습니다. Java 글꼴 조작 API에 대해 자세히 알아보려면 문서를 방문하고 소스 코드 샘플을 사용하여 API의 기능을 평가할 수 있습니다.