フォントを使用してテキストをレンダリングする

前の投稿では、Aspose.Font for .NETAPIを使用してCFFTrueType、および[Type1]をロードおよび保存する方法を説明しました。 5プログラムによるフォント。この記事では、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でメソッドを実装する方法を示しています。

  • グラフィックを描画するために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();
    }
}
  • 新しいメソッドDrawText()を作成して、テキストをSystem.Drawing.Bitmapオブジェクトに描画します。
// 完全な例とデータファイルについては、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;
    //すべてのグリフをギッドでペイントするループ
    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#を使用して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の詳細を調べることができます。

関連項目