merender teks menggunakan font

Di posting sebelumnya, Anda telah melihat cara menggunakan Aspose.Font for .NET API untuk memuat dan menyimpan CFF, TrueType, dan Type1 font secara terprogram. Pada artikel ini, Anda akan mempelajari cara merender teks dengan font TrueType dan Type1 menggunakan C#. Contoh kode akan menunjukkan cara membuat gambar JPG berdasarkan teks yang disediakan.

.NET Font Rendering API - Instalasi

Aspose.Font for .NET menyediakan mekanisme rendering font yang kuat untuk merender teks menggunakan font TrueType dan Type1. Anda dapat mengunduh API atau menginstalnya menggunakan NuGet.

PM> Install-Package Aspose.Font

Menerapkan Antarmuka Rendering Teks

Untuk mencapai rendering teks, Aspose.Font for .NET menyediakan antarmuka IGlyphOutlinePainter untuk menggambar mesin terbang. Langkah-langkah berikut menunjukkan cara menerapkan metode di IGlyphOutlinePainter.

// Untuk contoh lengkap dan file data, silakan buka 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();
    }
}
// Untuk contoh lengkap dan file data, silakan buka https://github.com/aspose-font/Aspose.Font-for-.NET
static void DrawText(string text, IFont font, double fontSize,
            Brush backgroundBrush, Brush textBrush, string outFile)
{
    //Dapatkan pengenal mesin terbang untuk setiap simbol di baris teks
    GlyphId[] gids = new GlyphId[text.Length];
   for (int i = 0; i < text.Length; i++)
        gids[i] = font.Encoding.DecodeToGid(text[i]);
    // mengatur pengaturan gambar umum
    double dpi = 300;

    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // menyiapkan bitmap keluaran
    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;
    //mendeklarasikan variabel koordinat dan gi sebelumnya
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //loop yang melukis setiap mesin terbang di gids
    foreach (GlyphId gid in gids)
    {
        // jika font berisi gid
        if (gid != null)
        {
            Glyph glyph = font.GlyphAccessor.GetGlyphById(gid);
            if (glyph == null)
                continue;

            // jalur yang menerima instruksi menggambar
            GraphicsPath path = new GraphicsPath();

            // Buat implementasi IGlyphOutlinePainter
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);

            // Buat perender
            Aspose.Font.Renderers.IGlyphRenderer renderer = new
                Aspose.Font.Renderers.GlyphOutlineRenderer(outlinePainter);

            // dapatkan properti mesin terbang umum
            double kerning = 0;

            // mendapatkan nilai kerning
            if (previousGid != null)
            {
                kerning = (font.Metrics.GetKerningValue(previousGid, gid) /
                           glyph.SourceResolution) * fontSize * resolutionCorrection;
                kerning += FontWidthToImageWith(font.Metrics.GetGlyphWidth(previousGid),
                        glyph.SourceResolution, fontSize);
            }

            // posisi mesin terbang - tingkatkan koordinat mesin terbang X sesuai dengan jarak kerning
            glyphXCoordinate += kerning;

            // Matriks penempatan mesin terbang
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // negatif karena sistem koordinat bitmap dimulai dari atas
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });

            // membuat mesin terbang saat ini
            renderer.RenderGlyph(font, gid, glyphMatrix);
            // mengisi jalan
            path.FillMode = FillMode.Winding;
            outGraphics.FillPath(textBrush, path);
        }
        //atur gid saat ini seperti sebelumnya untuk mendapatkan kerning yang benar untuk mesin terbang berikutnya
        previousGid = gid;
    }
    //Simpan hasil
    outBitmap.Save(outFile);
}
  • Tentukan metode utilitas untuk menghitung lebar font sesuai dengan lebar gambar.
// Untuk contoh lengkap dan file data, silakan buka 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;
}

Render Teks dengan TrueType Font menggunakan C#

Contoh kode berikut menunjukkan cara menggunakan implementasi yang disebutkan di atas untuk merender teks dengan font TrueType menggunakan C#.

// Untuk contoh lengkap dan file data, silakan buka 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");

Render Teks dengan Font Type1 menggunakan C

Contoh kode berikut menunjukkan cara merender teks dengan font Type1 menggunakan C#.

// Untuk contoh lengkap dan file data, silakan buka 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");

Kesimpulan

Dalam artikel ini, Anda telah mempelajari cara mengimplementasikan rendering teks dengan font TrueType atau Type1 menggunakan C#. Contoh kode telah menunjukkan cara menghasilkan gambar JPG berdasarkan teks yang disediakan. Anda dapat mempelajari lebih lanjut tentang Aspose.Font for .NET menggunakan dokumentasi.

Lihat juga