使用字體渲染文本

上一篇文章中,您了解瞭如何使用 Aspose.Font for .NET API 來加載和保存 CFFTrueTypeType1 字體編程。在本文中,您將學習如何使用 C# 呈現具有 TrueType 和 Type1 字體的文本。代碼示例將向您展示如何根據提供的文本生成 JPG 圖像。

.NET 字體渲染 API - 安裝

Aspose.Font for .NET 提供了強大的字體渲染機制,以便使用 TrueType 和 Type1 字體渲染文本。您可以 下載 API 或使用 NuGet 安裝它。

PM> Install-Package Aspose.Font

實現文本渲染接口

為了實現文本渲染,Aspose.Font for .NET提供了一個IGlyphOutlinePainter接口來繪製字形。以下步驟演示如何實現 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;
    //繪製 gids 中每個字形的循環
    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 設置為以前的 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# 渲染帶有 TrueType 字體的文本

下面的代碼示例顯示瞭如何使用上述實現來使用 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 圖像。您可以使用 文檔 探索更多關於 Aspose.Font for .NET 的信息。

也可以看看