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

이전 포스트에서 CFF, TrueType, [Type1] 불러오기 및 저장을 위해 Aspose.Font for .NET API를 사용하는 방법을 살펴보았습니다. 5 프로그래밍 방식으로 글꼴. 이 기사에서는 C#을 사용하여 TrueType 및 Type1 글꼴로 텍스트를 렌더링하는 방법을 배웁니다. 코드 샘플은 제공된 텍스트를 기반으로 JPG 이미지를 생성하는 방법을 보여줍니다.

.NET 글꼴 렌더링 API - 설치

Aspose.Font for .NET은 TrueType 및 Type1 글꼴을 사용하여 텍스트를 렌더링하기 위해 강력한 글꼴 렌더링 메커니즘을 제공합니다. API를 다운로드하거나 NuGet을 사용하여 설치할 수 있습니다.

PM> Install-Package Aspose.Font

텍스트 렌더링 인터페이스 구현

텍스트 렌더링을 달성하기 위해 .NET용 Aspose.Font는 글리프를 그리는 IGlyphOutlinePainter 인터페이스를 제공합니다. 다음 단계는 IGlyphOutlinePainter에서 메서드를 구현하는 방법을 보여줍니다.

  • 그래픽을 그리기 위해 System.Drawing.Drawing2D.GraphicsPath 유형의 개체가 필요한 GlyphOutlinePainter 클래스를 사용하여 IGlyphOutlinePainter 인터페이스 메서드를 구현합니다.
// 전체 예제 및 데이터 파일을 보려면 https://github.com/aspose-font/Aspose.Font-for-.NET으로 이동하십시오.
class GlyphOutlinePainter : IGlyphOutlinePainter
{
    private System.Drawing.Drawing2D.GraphicsPath _path;
    private System.Drawing.PointF _currentPoint;

    public GlyphOutlinePainter(System.Drawing.Drawing2D.GraphicsPath path)
    {
        _path = path;
    }

    public void MoveTo(MoveTo moveTo)
    {
        _path.CloseFigure();
        _currentPoint.X = (float)moveTo.X;
        _currentPoint.Y = (float)moveTo.Y;
    }

    public void LineTo(LineTo lineTo)
    {
        float x = (float)lineTo.X;
        float y = (float)lineTo.Y;
        _path.AddLine(_currentPoint.X, _currentPoint.Y, x, y);
        _currentPoint.X = x;
        _currentPoint.Y = y;
    }

    public void CurveTo(CurveTo curveTo)
    {
        float x3 = (float)curveTo.X3;
        float y3 = (float)curveTo.Y3;

        _path.AddBezier(
                  _currentPoint.X,
                  _currentPoint.Y,
                  (float)curveTo.X1,
                  (float)curveTo.Y1,
                  (float)curveTo.X2,
                  (float)curveTo.Y2,
                  x3,
                  y3);

        _currentPoint.X = x3;
        _currentPoint.Y = y3;
    }

    public void ClosePath()
    {
        _path.CloseFigure();
    }
}
// 전체 예제 및 데이터 파일을 보려면 https://github.com/aspose-font/Aspose.Font-for-.NET으로 이동하십시오.
static void DrawText(string text, IFont font, double fontSize,
            Brush backgroundBrush, Brush textBrush, string outFile)
{
    //텍스트 줄의 모든 기호에 대한 글리프 식별자 가져오기
    GlyphId[] gids = new GlyphId[text.Length];
    for (int i = 0; i < text.Length; i++)
        gids[i] = font.Encoding.DecodeToGid(text[i]);
    // 공통 도면 설정 지정
    double dpi = 300;

    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // 출력 비트맵 준비
    Bitmap outBitmap = new Bitmap(960, 720);
    outBitmap.SetResolution((float)dpi, (float)dpi);
    Graphics outGraphics = Graphics.FromImage(outBitmap);
    outGraphics.FillRectangle(backgroundBrush, 0, 0, outBitmap.Width, outBitmap.Height);
    outGraphics.SmoothingMode = SmoothingMode.HighQuality;
    //좌표 변수 및 이전 gid 선언
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //gid의 모든 글리프를 그리는 루프
    foreach (GlyphId gid in gids)
    {
        // 글꼴에 gid가 포함된 경우
        if (gid != null)
        {
            Glyph glyph = font.GlyphAccessor.GetGlyphById(gid);
            if (glyph == null)
                continue;

            // 그리기 지시를 받아들이는 경로
            GraphicsPath path = new GraphicsPath();

            // IGlyphOutlinePainter 구현 생성
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);

            // 렌더러 만들기
            Aspose.Font.Renderers.IGlyphRenderer renderer = new
                Aspose.Font.Renderers.GlyphOutlineRenderer(outlinePainter);

            // 공통 글리프 속성 얻기
            double kerning = 0;

            // 커닝 값 얻기
            if (previousGid != null)
            {
                kerning = (font.Metrics.GetKerningValue(previousGid, gid) /
                           glyph.SourceResolution) * fontSize * resolutionCorrection;
                kerning += FontWidthToImageWith(font.Metrics.GetGlyphWidth(previousGid),
                        glyph.SourceResolution, fontSize);
            }

            // 글리프 포지셔닝 - 커닝 거리에 따라 글리프 X 좌표 증가
            glyphXCoordinate += kerning;

            // 글리프 배치 매트릭스
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // 비트맵 좌표계가 맨 위에서 시작하기 때문에 음수
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });

            // 현재 글리프 렌더링
            renderer.RenderGlyph(font, gid, glyphMatrix);
            // 길을 채우다
            path.FillMode = FillMode.Winding;
            outGraphics.FillPath(textBrush, path);
        }
        //다음 글리프에 대한 올바른 커닝을 얻으려면 현재 gid를 이전으로 설정하십시오.
        previousGid = gid;
    }
    //결과 저장
    outBitmap.Save(outFile);
}
  • 이미지 너비에 따라 글꼴 너비를 계산하는 유틸리티 메서드를 정의합니다.
// 전체 예제 및 데이터 파일을 보려면 https://github.com/aspose-font/Aspose.Font-for-.NET으로 이동하십시오.
static double FontWidthToImageWith(double width, int fontSourceResulution, double fontSize, double dpi = 300)
{
    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    return (width / fontSourceResulution) * fontSize * resolutionCorrection;
}

C#을 사용하여 트루타입 글꼴로 텍스트 렌더링

다음 코드 샘플은 위에서 언급한 구현을 사용하여 C#을 사용하여 TrueType 글꼴로 텍스트를 렌더링하는 방법을 보여줍니다.

// 전체 예제 및 데이터 파일을 보려면 https://github.com/aspose-font/Aspose.Font-for-.NET으로 이동하십시오.
string dataDir = RunExamples.GetDataDir_Data();

string fileName1 = dataDir + "Montserrat-Bold.ttf"; //Font file name with full path
FontDefinition fd1 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName1)));
TtfFont ttfFont1 = Aspose.Font.Font.Open(fd1) as TtfFont;
            
string fileName2 = dataDir + "Lora-Bold.ttf"; //Font file name with full path
FontDefinition fd2 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName2)));
TtfFont ttfFont2 = Aspose.Font.Font.Open(fd2) as TtfFont;

DrawText("Hello world", ttfFont1, 14, Brushes.White, Brushes.Black, dataDir + "hello1_montserrat_out.jpg");
DrawText("Hello world", ttfFont2, 14, Brushes.Yellow, Brushes.Red, dataDir + "hello2_lora_out.jpg");

C#을 사용하여 Type1 글꼴로 텍스트 렌더링

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

// 전체 예제 및 데이터 파일을 보려면 https://github.com/aspose-font/Aspose.Font-for-.NET으로 이동하십시오.
string fileName = dataDir + "courier.pfb"; //Font file name with full path

FontDefinition fd = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
Type1Font font = Aspose.Font.Font.Open(fd) as Type1Font;
            

DrawText("Hello world", font, 14, Brushes.White, Brushes.Black, dataDir + "hello1_type1_out.jpg");
DrawText("Hello world", font, 14, Brushes.Yellow, Brushes.Red, dataDir + "hello2_type1_out.jpg");

결론

이 문서에서는 C#을 사용하여 TrueType 또는 Type1 글꼴로 텍스트 렌더링을 구현하는 방법을 배웠습니다. 코드 샘플은 제공된 텍스트를 기반으로 JPG 이미지를 생성하는 방법을 보여주었습니다. 문서를 사용하여 .NET용 Aspose.Font에 대해 자세히 알아볼 수 있습니다.

또한보십시오