Отрисовка текста с использованием шрифта TrueType | С++

Отрисовка текста

Для визуализации текста подсистеме рендеринга требуется реализация интерфейса Aspose.Font.Rendering.IGlyphOutlinePainter для рисования глифа. Этого можно достичь, выполнив следующие шаги.

  1. Реализуйте методы IGlyphOutlinePainter, создав класс GlyphOutlinePainter, которому требуется объект типа System.Drawing.Drawing2D.GraphicsPath для целей графического рисования. Реализация показана ниже.
 1For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
 2RenderingText::GlyphOutlinePainter::GlyphOutlinePainter(System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> path)
 3{
 4    _path = path;
 5}
 6
 7void RenderingText::GlyphOutlinePainter::MoveTo(System::SharedPtr<Aspose::Font::RenderingPath::MoveTo> moveTo)
 8{
 9    _path->CloseFigure();
10    _currentPoint.set_X((float)moveTo->get_X());
11    _currentPoint.set_Y((float)moveTo->get_Y());
12}
13
14void RenderingText::GlyphOutlinePainter::LineTo(System::SharedPtr<Aspose::Font::RenderingPath::LineTo> lineTo)
15{
16    float x = (float)lineTo->get_X();
17    float y = (float)lineTo->get_Y();
18    _path->AddLine(_currentPoint.get_X(), _currentPoint.get_Y(), x, y);
19    _currentPoint.set_X(x);
20    _currentPoint.set_Y(y);
21}
22
23void RenderingText::GlyphOutlinePainter::CurveTo(System::SharedPtr<Aspose::Font::RenderingPath::CurveTo> curveTo)
24{
25    float x3 = (float)curveTo->get_X3();
26    float y3 = (float)curveTo->get_Y3();
27    
28    _path->AddBezier(_currentPoint.get_X(), _currentPoint.get_Y(), (float)curveTo->get_X1(), (float)curveTo->get_Y1(), (float)curveTo->get_X2(), (float)curveTo->get_Y2(), x3, y3);
29    
30    _currentPoint.set_X(x3);
31    _currentPoint.set_Y(y3);
32}
33
34void RenderingText::GlyphOutlinePainter::ClosePath()
35{
36    _path->CloseFigure();
37}
38
39System::Object::shared_members_type Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::GetSharedMembers()
40{
41    auto result = System::Object::GetSharedMembers();
42    
43    result.Add("Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::_path", this->_path);
44    result.Add("Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::_currentPoint", this->_currentPoint);
45    
46    return result;
47}
  1. Создайте метод DrawText(), который рисует указанный текст в объект System.Drawing.Bitmap и сохраняет полученное растровое изображение на диске. Это будет включать в себя следующие шаги:

Вспомогательные шаги для этой стратегии

Реализация метода DrawText показана ниже.

  1. создайте служебный метод для расчета ширины шрифта по ширине изображения, как показано в примере кода ниже.
1For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
2double RenderingText::FontWidthToImageWith(double width, int32_t fontSourceResulution, double fontSize, double dpi /* = 300*/)
3{
4    double resolutionCorrection = dpi / 72;
5    // 72 is font's internal dpi
6    return (width / fontSourceResulution) * fontSize * resolutionCorrection;
7}

Вызов функции «Отрисовка текста»

Чтобы использовать приведенные выше реализации, можно выполнить следующий пример кода из метода Main консольного приложения.

 1For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
 2System::String dataDir = RunExamples::GetDataDir_Data();
 3    
 4System::String fileName1 = dataDir + u"Montserrat-Bold.ttf";
 5//Font file name with full path
 6System::SharedPtr<FontDefinition> fd1 = System::MakeObject<FontDefinition>(Aspose::Font::FontType::TTF, System::MakeObject<FontFileDefinition>(u"ttf", System::MakeObject<FileSystemStreamSource>(fileName1)));
 7System::SharedPtr<TtfFont> ttfFont1 = System::DynamicCast_noexcept<Aspose::Font::Ttf::TtfFont>(Aspose::Font::Font::Open(fd1));
 8    
 9System::String fileName2 = dataDir + u"Lora-Bold.ttf";
10//Font file name with full path
11System::SharedPtr<FontDefinition> fd2 = System::MakeObject<FontDefinition>(Aspose::Font::FontType::TTF, System::MakeObject<FontFileDefinition>(u"ttf", System::MakeObject<FileSystemStreamSource>(fileName2)));
12System::SharedPtr<TtfFont> ttfFont2 = System::DynamicCast_noexcept<Aspose::Font::Ttf::TtfFont>(Aspose::Font::Font::Open(fd2));
13    
14DrawText(u"Hello world", ttfFont1, 14, System::Drawing::Brushes::get_White(), System::Drawing::Brushes::get_Black(), dataDir + u"hello1_montserrat_out.jpg");
15DrawText(u"Hello world", ttfFont2, 14, System::Drawing::Brushes::get_Yellow(), System::Drawing::Brushes::get_Red(), dataDir + u"hello2_lora_out.jpg");
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.