hiển thị văn bản bằng cách sử dụng phông chữ

Trong bài đăng trước, bạn đã biết cách sử dụng API Aspose.Font for .NET để tải và lưu CFF, TrueTypeType1 phông chữ lập trình. Trong bài viết này, bạn sẽ tìm hiểu cách hiển thị văn bản bằng phông chữ TrueType và Type1 bằng C#. Các mẫu mã sẽ chỉ cho bạn cách tạo hình ảnh JPG dựa trên văn bản được cung cấp.

.NET Font Rendering API - Cài đặt

Aspose.Font cho .NET cung cấp cơ chế hiển thị phông chữ mạnh mẽ để hiển thị văn bản bằng phông chữ TrueType và Type1. Bạn có thể tải xuống API hoặc cài đặt nó bằng NuGet.

PM> Install-Package Aspose.Font

Triển khai giao diện kết xuất văn bản

Để đạt được kết xuất văn bản, Aspose.Font cho .NET cung cấp giao diện IGlyphOutlinePainter để vẽ các nét. Các bước sau đây trình bày cách triển khai các phương thức trong IGlyphOutlinePainter.

  • Triển khai các phương thức giao diện IGlyphOutlinePainter bằng cách sử dụng lớp GlyphOutlinePainter yêu cầu đối tượng loại System.Drawing.Drawing2D.GraphicsPath để vẽ đồ họa.
// Để biết các ví dụ và tệp dữ liệu đầy đủ, vui lòng truy cập 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();
    }
}
  • Tạo một phương thức mới DrawText() để vẽ văn bản vào đối tượng System.Drawing.Bitmap.
// Để biết các ví dụ và tệp dữ liệu đầy đủ, vui lòng truy cập https://github.com/aspose-font/Aspose.Font-for-.NET
static void DrawText(string text, IFont font, double fontSize,
            Brush backgroundBrush, Brush textBrush, string outFile)
{
    //Nhận số nhận dạng glyph cho mọi ký hiệu trong dòng văn bản
    GlyphId[] gids = new GlyphId[text.Length];
   for (int i = 0; i < text.Length; i++)
        gids[i] = font.Encoding.DecodeToGid(text[i]);
    // đặt cài đặt bản vẽ chung
    double dpi = 300;

    double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
    // chuẩn bị bitmap đầu ra
    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;
    //khai báo các biến tọa độ và gid trước đó
    GlyphId previousGid = null;
    double glyphXCoordinate = 0;
    double glyphYCoordinate = fontSize * resolutionCorrection;
    //vòng lặp vẽ mọi glyph trong gids
    foreach (GlyphId gid in gids)
    {
        // nếu phông chữ chứa gid
        if (gid != null)
        {
            Glyph glyph = font.GlyphAccessor.GetGlyphById(gid);
            if (glyph == null)
                continue;

            // đường dẫn chấp nhận hướng dẫn vẽ
            GraphicsPath path = new GraphicsPath();

            // Tạo triển khai IGlyphOutlinePainter
            GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);

            // Tạo trình kết xuất
            Aspose.Font.Renderers.IGlyphRenderer renderer = new
                Aspose.Font.Renderers.GlyphOutlineRenderer(outlinePainter);

            // nhận các thuộc tính glyph phổ biến
            double kerning = 0;

            // lấy giá trị kerning
            if (previousGid != null)
            {
                kerning = (font.Metrics.GetKerningValue(previousGid, gid) /
                           glyph.SourceResolution) * fontSize * resolutionCorrection;
                kerning += FontWidthToImageWith(font.Metrics.GetGlyphWidth(previousGid),
                        glyph.SourceResolution, fontSize);
            }

            // định vị glyph - tăng tọa độ glyph X theo khoảng cách kerning
            glyphXCoordinate += kerning;

            // Ma trận vị trí Glyph
            TransformationMatrix glyphMatrix =
                new TransformationMatrix(
                    new double[]
                            {
                                    fontSize*resolutionCorrection,
                                    0,
                                    0,
                                // âm vì hệ tọa độ bitmap bắt đầu từ đầu
                                    - fontSize*resolutionCorrection,
                                    glyphXCoordinate,
                                    glyphYCoordinate
                            });

            // hiển thị glyph hiện tại
            renderer.RenderGlyph(font, gid, glyphMatrix);
            // điền vào đường dẫn
            path.FillMode = FillMode.Winding;
            outGraphics.FillPath(textBrush, path);
        }
        //đặt gid hiện tại như trước đó để có được kerning chính xác cho glyph tiếp theo
        previousGid = gid;
    }
    //Lưu kết quả
    outBitmap.Save(outFile);
}
  • Xác định một phương thức tiện ích để tính chiều rộng của phông chữ theo chiều rộng của hình ảnh.
// Để biết các ví dụ và tệp dữ liệu đầy đủ, vui lòng truy cập 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;
}

Kết xuất văn bản với Phông chữ TrueType bằng C#

Mẫu mã sau đây cho biết cách sử dụng triển khai nêu trên để hiển thị văn bản bằng phông chữ TrueType bằng C#.

// Để biết các ví dụ và tệp dữ liệu đầy đủ, vui lòng truy cập 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");

Kết xuất văn bản với Phông chữ Type1 bằng C#

Mẫu mã sau đây cho biết cách hiển thị văn bản bằng phông chữ Type1 bằng C#.

// Để biết các ví dụ và tệp dữ liệu đầy đủ, vui lòng truy cập 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");

Sự kết luận

Trong bài viết này, bạn đã học cách triển khai hiển thị văn bản bằng phông chữ TrueType hoặc Type1 bằng C#. Các mẫu mã đã chỉ ra cách tạo hình ảnh JPG dựa trên văn bản được cung cấp. Bạn có thể khám phá thêm về Aspose.Font cho .NET bằng cách sử dụng tài liệu.

Xem thêm