Using Glyph objects | API Solution for .NET

Working with glyphs is crucial when coding fonts as it is their unit. When the basic information about glyphs is explained in the article of the What is font paragraph, here we are going to teach you the functionality of Aspose.Font for working with glyphs and the Glyph objects in particular.

Glyph object

Glyphs of any font are represented by Glyph type in Aspose.Font library. So, Glyph type is a universal object for font glyphs, independently from font format(TrueType, Compact Font Format, etc).

The functionality provided by the Glyph object

What functionality does this object provide for us?

This question is answered by the properties it has.

Let’s have an example with the next code snippet that shows how to calculate the width for the text “Hello world” in pixels when the font size is 10.

Add the next namespaces at the head of the file:

1using Aspose.Font.Glyphs;			
2using Aspose.Font.Font font;

Then you need to take the next steps:

 1    Aspose.Font.Font font;
 3    // Declare text and other constants
 4    const string text = "Hello world";
 5    const int fontSize = 10;
 7    //Declare a variable for string width
 8    double width = 0;     
10    //Get glyphs for each letter in the text and calculate the width for the whole text
11    //The same result can be achieved using the method font.Metrics.MeasureString (text, fontSize)
12    foreach (char symbol in text)
13    {
14        GlyphId gid = font.Encoding.DecodeToGid(symbol);
15        Glyph glyph = font.GetGlyphById(gid);
16        width += (glyph.WidthVectorX / font.Metrics.UnitsPerEM) * fontSize;
17    }

To get the glyph’s Bounding box use the GlyphBBox property of the Glyph object.

To get a visual representation of glyphs you need to know the coordinates for all glyphs’ points.

How to get coordinates for all glyph points from the Glyph object?

The next properties, IsEmpty and Path were designed for this case.

Property IsEmpty is auxiliary. It tells us whether the glyph’s path is empty, or in other words glyph has no drawing instructions at all. If it has the value false, it’s time to construct the whole glyph’s figure using the very useful property Path.

In the concept of Aspose.Font library the representation of any glyph is divided into the simplest graphic primitives, called segments, and represented by interface IPathSegment. Interface IPathSegment is a base abstract graphic primitive.

Concrete graphic primitives are represented by such types as MoveTo, LineTo, CurveTo, and ClosePath.

Type ClosePath is used to indicate the end of the current graphic contour.

Types MoveTo, LineTo, and CurveTo by their definition correspond with the identical postscript operators.

Also, the types MoveTo and LineTo by their definition correspond to the functions MoveToEx() and LineTo() from windows GDI lib, type CurveTo is used to describe Bézier curves.

Glyph property Path provides us with a collection of all graphic primitives for that glyph.

Property Path has type SegmentPath and every object of this type has property Segments of type PathSegmentCollection. This property Segments returns all the graphic primitives which object SegmentPath includes. In other words, we can get all the graphic primitives for the glyph using the entry glyph.Path.Segments.

The next example calculates all the points which glyph has and stores them in variable points, which represents an array of objects with Point type.

The logic used by this sample is simple and it doesn’t extract glyph contours. To get these contours using type ClosePath must be added to segments processing.

Add the next namespaces at the head of the file:

1using System.Collections.Generic;
2using System.Drawing;
3using Aspose.Font.Glyphs;
4using Aspose.Font.RenderingPath;

Then you need to take the next steps:

 1    Glyph glyph;
 3    //Declare resultant list with points
 4    List<Point> points = new List<Point>();
 6    //Init service reference on IPathSegment
 7    IPathSegment prevSegment = null;
 9    //Iterate all glyph path segments and collect points
10    foreach (IPathSegment segment in glyph.Path.Segments)
11    {
12        if ((segment is LineTo)
13            || (segment is CurveTo))
14        {
15            if (prevSegment is MoveTo)
16            {
17                MoveTo moveTo = prevSegment as MoveTo;
18                AddPoint((int)moveTo.X, (int)moveTo.Y, points);
19            }
20            if (segment is LineTo)
21            {
22                LineTo line = segment as LineTo;
23                AddPoint((int)line.X, (int)line.Y, points);
24            }
25            else if (segment is CurveTo)
26            {
27                CurveTo curve = segment as CurveTo;
28                AddPoint((int)curve.X1, (int)curve.Y1, points);
29                AddPoint((int)curve.X2, (int)curve.Y2, points);
30                AddPoint((int)curve.X3, (int)curve.Y3, points);
31            }
32        }
33        prevSegment = segment;
34    }	
36    void AddPoint(int x, int y, List<Point> points)
37    {
38        Point p = new Point();
39        p.X = x;
40        p.Y = y;
41        points.Add(p);
42    }

How to calculate kerning value for glyphs?

Another Glyph metric but the one that is not supplied by the Glyph-type object. Here we are talking about kerning. Such a characteristic as kerning, applies not to one but to a pair of glyphs. So to calculate kerning you need to use the identifier not of one but of two glyphs.

Interface IFontMetrics in Aspose.Font library defines method GetKerningValue() which takes glyph identifiers for a glyphs pair and returns a kerning value, related to that pair. If no kerning information exists for glyphs pair, the method returns 0. Implementation of IFontMetrics interface exists for all classes of supported font formats and it is accessible using property Metrics.

The next snippet calculates the kerning value for glyphs associated with symbols ‘A’ and ‘C’:

1    Font font; 
3    double kerning = font.Metrics.GetKerningValue(font.Encoding.UnicodeToGid('A'), font.Encoding.UnicodeToGid('C'));	

How To obtain glyphs from font?

Any glyph in a font can be accessed by a special glyph identifier. This rule is true for any font format.

Glyph identifiers GlyphId can be of two types: integer or string. These GlyphId data types are linked with such glyph characteristics as glyph index and glyph name correspondingly.

Also, each glyph has an index equal to its numbering in the font. An important moment is that the numbering starts not from 1 but from 0 so if a font contains of 15 glyphs, they have Glyph IDs 0–14.

The glyphs usually also have glyph names which are brief ASCII text labels without spaces. For example, the glyph name for symbol “+” is “plus”.

So the data type integer corresponds with such a characteristic of the glyph as glyph index, and the data type string corresponds with the name of the glyph. Each glyph of a font represents the image of the symbol which this glyph is associated with so the glyph is linked not only to its identifier but to the unique code corresponding to this symbol.

The relation between character codes and glyph identifiers is called encoding. Glyphs in the font can be accessed directly by glyph identifiers or using encoding.

In the last case first, the glyph identifier based on the character code is calculated. Then the glyph corresponding to the calculated identifier is received.

What type of glyph identifier should be used to access the desired glyph?

It depends on the format of the font. Glyphs in fonts of Type 1 Font Format and Compact Font Format (CFF) are accessible by the glyph name. Actually, glyphs in fonts of these formats are kept as an array and are physically accessible via numerical index but on the higher logical level for getting a glyph its name is used.

TrueType fonts use integer type for glyph identifiers. If the TrueType font has ‘post’ table, glyph name or a glyph identifier of string type can be used to access the glyph.

Retrieving glyphs from font using Aspose.Font library.

Aspose.Font library introduces namespace Aspose.Font.Glyphs where glyphs, glyph identifiers, and other objects are placed. Class GlyphId is a base abstract class for glyph identifiers. Objects of that class are used to get desired glyphs.

Glyph identifiers for integers and a string type are represented by classes GlyphUInt32Id and GlyphStringId correspondingly.

Both these classes are inherited from the base abstract class GlyphId and particularly the objects of this abstract class GlyphId are passed in the function of the library for access to the needed glyph. So to get the required glyph you create a GlyphUInt32Id or GlyphStringId-type object and then pass the created object to one of the functions that are designed for retrieving glyphs.

In most cases, you do not know which glyph identifier corresponds to the specific character so to get the glyph identifier you need to find the relation between character code and glyph identifier.

As it was mentioned above, font encoding is responsible for such relations. Base font encoding functionality is defined by the IFontEncoding interface.

Base interface IFont implemented by all font classes defines property Encoding of type IFontEncoding, so any font object created by Aspose.Font library provides implementation for IFontEncoding functionality by the property Encoding.

Next methods were designed to calculate glyph identifier for a character code: UnicodeToGid(), DecodeToGid and DecodeToGidParameterized:

After you get a glyph identifier or in other words a reference to the GlyphId object, you can get the glyph associated with this GlyphId using functionality, defined by the interface IGlyphAccessor.

The interface IGlyphAccessor is implemented by any class, derived from the base Font class and it’s accessible by the IFont.GlyphAccessor property.

Interface IGlyphAccessor defines the method GetGlyphById(). Use this method to get the glyph for GlyphId passed.

The example of how to use the GetGlyphById method to get GlyphId and the corresponding glyph is included in the example from the The functionality provided by the Glyph object chapter.

The next 2 methods of this interface are designed to get glyph identifiers:

Also, interface IGlyphAccessor defines the property GlyphIdType which tells us what data type, integer, or string имеет glyph identifier.

Support for retrieving glyphs is more powerful for TrueType fonts. Here you can find the information on how to get access to font glyphs.

All the examples of using the Aspose.Font are stored in Aspose.Font.Examples.sln solution, in the net-examples of the Aspose.Font Documentation

If you have any issues, you may post them at the Aspose.Font.Product Family section of the Free Support Forum and within a few hours our support team will clear everything up for you.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.