Text mit Schriftarten rendern

Im vorherigen Beitrag haben Sie gesehen, wie Sie die API Aspose.Font for .NET zum Laden und Speichern von CFF, TrueType und [Type1] verwenden. 5 Schriftarten programmgesteuert. In diesem Artikel erfahren Sie, wie Sie mit C# Text mit TrueType und Type1-Schriftarten rendern. Die Codebeispiele zeigen Ihnen, wie Sie basierend auf dem bereitgestellten Text ein JPG Bild generieren.

.NET API zum Rendern von Schriftarten – Installation

Aspose.Font for .NET bietet einen leistungsstarken Mechanismus zum Rendern von Schriftarten, um den Text mit TrueType und Type1-Schriftarten zu rendern. Sie können die API herunterladen oder sie mit NuGet installieren lassen.

PM> Install-Package Aspose.Font

Implementieren Sie die Text-Rendering-Schnittstelle

Um die Textwiedergabe zu erreichen, bietet Aspose.Font for .NET eine IGlyphOutlinePainter-Schnittstelle zum Zeichnen der Glyphen. Die folgenden Schritte zeigen, wie die Methoden in IGlyphOutlinePainter implementiert werden.

  • Implementieren Sie die IGlyphOutlinePainter-Schnittstellenmethoden mithilfe der GlyphOutlinePainter Klasse, die ein Objekt vom Typ System.Drawing.Drawing2D.GraphicsPath zum Zeichnen von Grafiken erfordert.
// Vollständige Beispiele und Datendateien finden Sie unter 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();
    }
}
// Vollständige Beispiele und Datendateien finden Sie unter https://github.com/aspose-font/Aspose.Font-for-.NET
static void DrawText(string text, IFont font, double fontSize,
            Brush backgroundBrush, Brush textBrush, string outFile)
{
    //Holen Sie sich Glyphen-Identifikatoren für jedes Symbol in der Textzeile
    GlyphId[] gids = new GlyphId[text.Length];
    for (int i = 0; i < text.Length; i++)
        gids[i] = font.Encoding.DecodeToGid(text[i]);
    // allgemeine Zeichnungseinstellungen festlegen
    double dpi = 300;

    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // Ausgabe-Bitmap vorbereiten
    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;
    //deklarieren Sie Koordinatenvariablen und vorherige gid
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //Schleife, die jede Glyphe in Gids malt
    foreach (GlyphId gid in gids)
    {
        // wenn die Schriftart die gid enthält
        if (gid != null)
        {
            Glyph glyph = font.GlyphAccessor.GetGlyphById(gid);
            if (glyph == null)
                continue;

            // Pfad, der Zeichnungsanweisungen akzeptiert
            GraphicsPath path = new GraphicsPath();

            // Erstellen Sie eine IGlyphOutlinePainter-Implementierung
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);

            // Erstellen Sie den Renderer
            Aspose.Font.Renderers.IGlyphRenderer renderer = new
                Aspose.Font.Renderers.GlyphOutlineRenderer(outlinePainter);

            // allgemeine Glypheneigenschaften erhalten
            double kerning = 0;

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

            // Glyphenpositionierung - Erhöhen Sie die X-Koordinate der Glyphe entsprechend dem Kerning-Abstand
            glyphXCoordinate += kerning;

            // Glyphenplatzierungsmatrix
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // negativ, da das Bitmap-Koordinatensystem von oben beginnt
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });

            // Aktuelle Glyphe rendern
            renderer.RenderGlyph(font, gid, glyphMatrix);
            // den Weg füllen
            path.FillMode = FillMode.Winding;
            outGraphics.FillPath(textBrush, path);
        }
        //setze die aktuelle gid wie zuvor, um das richtige Kerning für die nächste Glyphe zu erhalten
        previousGid = gid;
    }
    //Ergebnisse speichern
    outBitmap.Save(outFile);
}
  • Definieren Sie eine Utility methode, um die Breite der Schriftart entsprechend der Breite des Bildes zu berechnen.
// Vollständige Beispiele und Datendateien finden Sie unter 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;
}

Rendern von Text mit TrueType-Schriftarten mit C#

Das folgende Codebeispiel zeigt, wie die oben genannte Implementierung zum Rendern von Text mit einer TrueType-Schriftart mithilfe von C# verwendet wird.

// Vollständige Beispiele und Datendateien finden Sie unter 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");

Text mit Type1-Schriftart mit C# rendern

Das folgende Codebeispiel zeigt, wie Text mit einer Type1-Schriftart mit C# gerendert wird.

// Vollständige Beispiele und Datendateien finden Sie unter 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");

Fazit

In diesem Artikel haben Sie gelernt, wie Sie das Rendern von Text mit einer TrueType oder Type1-Schriftart mithilfe von C# implementieren. Die Codebeispiele haben gezeigt, wie JPG Bilder basierend auf dem bereitgestellten Text generiert werden. Weitere Informationen zu Aspose.Font for .NET finden Sie in der Dokumentation.

Siehe auch