Renderizar fuente truetype c++

Los caracteres son símbolos que explican el significado de diferentes palabras. Puede representar diferentes caracteres de texto con fuentes TrueType usando C++ con Aspose.Font for C++ API. Admite diferentes funciones de representación de texto, incluidas TrueType, Type1, OTF, EOT y otras fuentes. Exploremos cómo usar las funciones de representación de texto con unas pocas llamadas simples a la API. Estaremos cubriendo el tema bajo los siguientes encabezados:

API de representación de fuentes TrueType de C++: instalación

Teniendo en cuenta la popularidad y la demanda de la plataforma C++, hemos introducido características muy útiles en Aspose.Font for C++ API. Para representar fuentes TrueType en sus aplicaciones, debe configurar la API descargándola de Nuevas versiones, o puede instalarla a través de NuGet usando el siguiente comando:

Install-Package Aspose.Font.Cpp

Implementar la interfaz para dibujar glifos para renderizar fuentes TrueType usando C++

En primer lugar, debe implementar IGlyphOutlinePainter en el espacio de nombres Aspose.Font.Rendering. Siga los pasos a continuación para la implementación de métodos y clases:

  1. Crea una clase llamada GlyphOutlinePainter
  2. Use System.Drawing.Drawing2D.GraphicsPath para dibujar gráficos

A continuación se muestra el fragmento de código C++ para la implementación de la interfaz para dibujar glifos:

For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
RenderingText::GlyphOutlinePainter::GlyphOutlinePainter(System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> path)
{
    _path = path;
}

void RenderingText::GlyphOutlinePainter::MoveTo(System::SharedPtr<Aspose::Font::RenderingPath::MoveTo> moveTo)
{
    _path->CloseFigure();
    _currentPoint.set_X((float)moveTo->get_X());
    _currentPoint.set_Y((float)moveTo->get_Y());
}

void RenderingText::GlyphOutlinePainter::LineTo(System::SharedPtr<Aspose::Font::RenderingPath::LineTo> lineTo)
{
    float x = (float)lineTo->get_X();
    float y = (float)lineTo->get_Y();
    _path->AddLine(_currentPoint.get_X(), _currentPoint.get_Y(), x, y);
    _currentPoint.set_X(x);
    _currentPoint.set_Y(y);
}

void RenderingText::GlyphOutlinePainter::CurveTo(System::SharedPtr<Aspose::Font::RenderingPath::CurveTo> curveTo)
{
    float x3 = (float)curveTo->get_X3();
    float y3 = (float)curveTo->get_Y3();
    
    _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);
    
    _currentPoint.set_X(x3);
    _currentPoint.set_Y(y3);
}

void RenderingText::GlyphOutlinePainter::ClosePath()
{
    _path->CloseFigure();
}

System::Object::shared_members_type Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::GetSharedMembers()
{
    auto result = System::Object::GetSharedMembers();
    
    result.Add("Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::_path", this->_path);
    result.Add("Aspose::Font::Examples::WorkingWithTrueTypeAndOpenTypeFonts::RenderingText::GlyphOutlinePainter::_currentPoint", this->_currentPoint);
    
    return result;
}

En segundo lugar, cree un método con el nombre DrawText con los siguientes pasos:

  1. Bucle a través de los símbolos en la cadena de texto
  2. Obtener GID como glifo identificado para cada símbolo
  3. Cree GlyphOutlinePainter y páselo al objeto GlyphOutlineRenderer
  4. Especifique las coordenadas del Glifo con el objeto Matriz

Además, después de seguir todos estos pasos, cree un método de utilidad para el cálculo de las dimensiones de la fuente en la imagen como se explica en el siguiente fragmento de código de C++:

For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
double RenderingText::FontWidthToImageWith(double width, int32_t fontSourceResulution, double fontSize, double dpi /* = 300*/)
{
    double resolutionCorrection = dpi / 72;
    // 72 es el ppp interno de la fuente
    return (width / fontSourceResulution) * fontSize * resolutionCorrection;
}

Renderizar texto con fuente TrueType usando C++

Hemos implementado la funcionalidad requerida para la representación de texto con fuentes TrueType. Ahora llamemos a los métodos usando Aspose.Font for C++ como el fragmento de código a continuación:

For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-C
System::String dataDir = RunExamples::GetDataDir_Data();
    
System::String fileName1 = dataDir + u"Montserrat-Bold.ttf";
//Nombre de archivo de fuente con ruta completa
System::SharedPtr<FontDefinition> fd1 = System::MakeObject<FontDefinition>(Aspose::Font::FontType::TTF, System::MakeObject<FontFileDefinition>(u"ttf", System::MakeObject<FileSystemStreamSource>(fileName1)));
System::SharedPtr<TtfFont> ttfFont1 = System::DynamicCast_noexcept<Aspose::Font::Ttf::TtfFont>(Aspose::Font::Font::Open(fd1));
    
System::String fileName2 = dataDir + u"Lora-Bold.ttf";
//Nombre de archivo de fuente con ruta completa
System::SharedPtr<FontDefinition> fd2 = System::MakeObject<FontDefinition>(Aspose::Font::FontType::TTF, System::MakeObject<FontFileDefinition>(u"ttf", System::MakeObject<FileSystemStreamSource>(fileName2)));
System::SharedPtr<TtfFont> ttfFont2 = System::DynamicCast_noexcept<Aspose::Font::Ttf::TtfFont>(Aspose::Font::Font::Open(fd2));
    
DrawText(u"Hello world", ttfFont1, 14, System::Drawing::Brushes::get_White(), System::Drawing::Brushes::get_Black(), dataDir + u"hello1_montserrat_out.jpg");
DrawText(u"Hello world", ttfFont2, 14, System::Drawing::Brushes::get_Yellow(), System::Drawing::Brushes::get_Red(), dataDir + u"hello2_lora_out.jpg");

Conclusión

En este artículo, ha aprendido a representar texto utilizando fuentes TrueType con C++. ¿Está interesado en obtener más información sobre las características que ofrece Aspose.Font for C++? Puede conocer más detalles explorando Referencias de API o Documentación del producto. Sin embargo, si tiene alguna ambigüedad o necesita ayuda, no dude en comunicarse con nosotros a través de Foros de soporte gratuitos. ¡Esperamos poder interactuar con usted!

Ver también