Fonts & text
A font is (in simple terms) a collection of shapes used to draw text.
A glyph is one of these shapes.
There can be multiple glyphs for the same character
(alternates to be used in different contexts, for example),
or a glyph can be a ligature of multiple characters.
Converting text to positioned glyphs is shaping.
Cairo itself provides a “toy” text API that only does simple shaping:
no ligature or kerning;
one glyph per character,
positioned by moving the cursor by the X and Y advance of each glyph.
It is expected that most applications will need to
use Pango or a similar library in conjunction with cairo
for more comprehensive font handling and text layout.
Font faces
Note
At the moment cairocffi only supports cairo’s “toy” font selection API.
FontFace objects of other types could be obtained
eg. from Context.get_font_face(),
but they can not be instantiated directly.
-
class cairocffi.FontFace
The base class for all font face types.
Should not be instantiated directly, but see CFFI API.
An instance may be returned for cairo font face types
that are not (yet) defined in cairocffi.
ToyFontFace
-
class cairocffi.ToyFontFace(family='', slant=0, weight=0)
Creates a font face from a triplet of family, slant, and weight.
These font faces are used in implementation of cairo’s “toy” font API.
If family is the zero-length string "",
the platform-specific default family is assumed.
The default family then can be queried using get_family().
The Context.select_font_face() method uses this to create font faces.
See that method for limitations and other details of toy font faces.
Parameters: |
- family – a font family name, as an Unicode or UTF-8 string.
- slant – The Font slant string for the font face.
- weight – The Font weight string for the font face.
|
-
get_family()
Return this font face’s family name.
-
get_slant()
Return this font face’s Font slant string.
-
get_weight()
Return this font face’s Font weight string.
ScaledFont
-
class cairocffi.ScaledFont(font_face, font_matrix=None, ctm=None, options=None)
Creates a ScaledFont object from a font face and matrices
that describe the size of the font
and the environment in which it will be used.
Parameters: |
- font_face – A FontFace object.
- font_matrix (Matrix) – Font space to user space transformation matrix for the font.
In the simplest case of a N point font,
this matrix is just a scale by N,
but it can also be used to shear the font
or stretch it unequally along the two axes.
If omitted, a scale by 10 matrix is assumed (ie. a 10 point font size).
See Context.set_font_matrix.
- ctm (Matrix) – User to device transformation matrix with which the font will be used.
If omitted, an identity matrix is assumed.
- options – The FontOptions object to use
when getting metrics for the font and rendering with it.
If omitted, the default options are assumed.
|
-
get_font_face()
Return the font face that this scaled font uses.
Returns: | A new instance of FontFace (or one of its sub-classes).
Might wrap be the same font face passed to ScaledFont,
but this does not hold true for all possible cases. |
-
get_font_options()
Copies the scaled font’s options.
-
get_font_matrix()
Copies the scaled font’s font matrix.
-
get_ctm()
Copies the scaled font’s font current transform matrix.
Note that the translation offsets (x0, y0) of the CTM
are ignored by ScaledFont.
So, the matrix this method returns always has 0 as x0 and y0.
-
get_scale_matrix()
Copies the scaled font’s scaled matrix.
The scale matrix is product of the font matrix
and the ctm associated with the scaled font,
and hence is the matrix mapping from font space to device space.
-
extents()
Return the scaled font’s extents.
See Context.font_extents().
Returns: | A (ascent, descent, height, max_x_advance, max_y_advance)
tuple of floats. |
-
text_extents(text)
Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the “inked” portion of the text,
(as it would be drawn by show_text()).
Additionally, the x_advance and y_advance values
indicate the amount by which the current point would be advanced
by show_text().
Parameters: | text – The text to measure, as an Unicode or UTF-8 string. |
Returns: | A (x_bearing, y_bearing, width, height, x_advance, y_advance)
tuple of floats.
See Context.text_extents() for details. |
-
glyph_extents(glyphs)
Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the “inked” portion of the glyphs,
(as it would be drawn by show_glyphs()).
Additionally, the x_advance and y_advance values
indicate the amount by which the current point would be advanced
by show_glyphs().
Parameters: | glyphs – A list of glyphs, as returned by text_to_glyphs().
Each glyph is a (glyph_id, x, y) tuple
of an integer and two floats. |
Returns: | A (x_bearing, y_bearing, width, height, x_advance, y_advance)
tuple of floats.
See Context.text_extents() for details. |
-
text_to_glyphs(x, y, text, with_clusters)
Converts a string of text to a list of glyphs,
optionally with cluster mapping,
that can be used to render later using this scaled font.
The output values can be readily passed to
Context.show_text_glyphs(), Context.show_glyphs()
or related methods,
assuming that the exact same ScaledFont
is used for the operation.
Parameters: |
- x (float) – X position to place first glyph.
- y (float) – Y position to place first glyph.
- text – The text to convert, as an Unicode or UTF-8 string.
- with_clusters (bool) – Whether to compute the cluster mapping.
|
Returns: | A (glyphs, clusters, clusters_flags) tuple
if with_clusters is true, otherwise just glyphs.
See Context.show_text_glyphs() for the data structure.
|
Note
This method is part of
what the cairo designers call the “toy” text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See Fonts & text for details
and Context.show_glyphs()
for the “real” text display API in cairo.
FontOptions
-
class cairocffi.FontOptions(**values)
An opaque object holding all options that are used when rendering fonts.
Individual features of a FontOptions
can be set or accessed using method
named set_FEATURE_NAME() and get_FEATURE_NAME(),
like set_antialias() and get_antialias().
New features may be added to FontOptions in the future.
For this reason, ==, copy(), merge(), and hash()
should be used to check for equality copy,, merge,
or compute a hash value of FontOptions objects.
Parameters: | values – Call the corresponding set_FEATURE_NAME() methods
after creating a new FontOptions:
options = FontOptions()
options.set_antialias(cairocffi.ANTIALIAS_BEST)
assert FontOptions(antialias=cairocffi.ANTIALIAS_BEST) == options
|
-
copy()
Return a new FontOptions with the same values.
-
merge(other)
Merges non-default options from other,
replacing existing values.
This operation can be thought of as somewhat similar
to compositing other onto options
with the operation of OVER.
-
set_antialias(antialias)
Changes the Antialiasing mode for the font options object.
This specifies the type of antialiasing to do when rendering text.
-
get_antialias()
Return the Antialiasing mode string for the font options object.
-
set_subpixel_order(subpixel_order)
Changes the Subpixel order for the font options object.
The subpixel order specifies the order of color elements
within each pixel on the display device
when rendering with an antialiasing mode of
SUBPIXEL.
-
get_subpixel_order()
Return the Subpixel order string
for the font options object.
-
set_hint_style(hint_style)
Changes the Hint style for the font options object.
This controls whether to fit font outlines to the pixel grid,
and if so, whether to optimize for fidelity or contrast.
-
get_hint_style()
Return the Hint style string for the font options object.
-
set_hint_metrics(hint_metrics)
Changes the Metrics hinting mode for the font options object.
This controls whether metrics are quantized
to integer values in device units.
-
get_hint_metrics()
Return the Metrics hinting mode string
for the font options object.
Enumerated values
Some parameters or return values in the cairo API
only have a fixed, finite set of valid values.
These are represented as enumerated types in C, and as integers in CFFI.
Users are encouraged to use the constants defined here
in the cairocffi module
rather than literal integers.
For example:
surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400)
Content
Used to describe the content that a Surface will contain,
whether color information, alpha information (translucence vs. opacity),
or both.
-
cairocffi.CONTENT_COLOR
The surface will hold color content only.
-
cairocffi.CONTENT_ALPHA
The surface will hold alpha content only.
-
cairocffi.CONTENT_COLOR_ALPHA
The surface will hold color and alpha content.
Compositiong operator
Used to set the compositing operator for all cairo drawing operations.
The default operator is OPERATOR_OVER.
The operators marked as unbounded modify their destination
even outside of the mask layer
(that is, their effect is not bound by the mask layer).
However, their effect can still be limited by way of clipping.
To keep things simple, the operator descriptions here
document the behavior for when both source and destination are either
fully transparent or fully opaque.
The actual implementation works for translucent layers too.
For a more detailed explanation of the effects of each operator,
including the mathematical definitions,
see http://cairographics.org/operators/.
-
cairocffi.OPERATOR_CLEAR
Clear destination layer. (bounded)
-
cairocffi.OPERATOR_SOURCE
Replace destination layer. (bounded)
-
cairocffi.OPERATOR_OVER
Draw source layer on top of destination layer. (bounded)
-
cairocffi.OPERATOR_IN
Draw source where there was destination content. (unbounded)
-
cairocffi.OPERATOR_OUT
Draw source where there was no destination content. (unbounded)
-
cairocffi.OPERATOR_ATOP
Draw source on top of destination content and only there.
-
cairocffi.OPERATOR_DEST
Ignore the source.
-
cairocffi.OPERATOR_DEST_OVER
Draw destination on top of source.
-
cairocffi.OPERATOR_DEST_IN
Leave destination only where there was source content. (unbounded)
-
cairocffi.OPERATOR_DEST_OUT
Leave destination only where there was no source content.
-
cairocffi.OPERATOR_DEST_ATOP
Leave destination on top of source content and only there. (unbounded)
-
cairocffi.OPERATOR_XOR
Source and destination are shown where there is only one of them.
-
cairocffi.OPERATOR_ADD
Source and destination layers are accumulated.
-
cairocffi.OPERATOR_SATURATE
Like OPERATOR_OVER,
but assuming source and destination are disjoint geometries.
-
cairocffi.OPERATOR_MULTIPLY
Source and destination layers are multiplied.
This causes the result to be at least as dark as the darker inputs.
(Since 1.10)
-
cairocffi.OPERATOR_SCREEN
Source and destination are complemented and multiplied.
This causes the result to be at least as light as the lighter inputs.
(Since cairo 1.10)
-
cairocffi.OPERATOR_OVERLAY
Multiplies or screens, depending on the lightness of the destination color.
(Since cairo 1.10)
-
cairocffi.OPERATOR_DARKEN
Replaces the destination with the source if it is darker,
otherwise keeps the source. (Since cairo 1.10)
-
cairocffi.OPERATOR_LIGHTEN
Replaces the destination with the source if it is lighter,
otherwise keeps the source. (Since cairo 1.10)
-
cairocffi.OPERATOR_COLOR_DODGE
Brightens the destination color to reflect the source color.
(Since cairo 1.10)
-
cairocffi.OPERATOR_COLOR_BURN
Darkens the destination color to reflect the source color.
(Since cairo 1.10)
-
cairocffi.OPERATOR_HARD_LIGHT
Multiplies or screens, dependent on source color. (Since cairo 1.10)
-
cairocffi.OPERATOR_SOFT_LIGHT
Darkens or lightens, dependent on source color. (Since cairo 1.10)
-
cairocffi.OPERATOR_DIFFERENCE
Takes the difference of the source and destination color.
(Since cairo 1.10)
-
cairocffi.OPERATOR_EXCLUSION
Produces an effect similar to difference, but with lower contrast.
(Since cairo 1.10)
-
cairocffi.OPERATOR_HSL_HUE
Creates a color with the hue of the source
and the saturation and luminosity of the target. (Since cairo 1.10)
-
cairocffi.OPERATOR_HSL_SATURATION
Creates a color with the saturation of the source
and the hue and luminosity of the target.
Painting with this mode onto a gray area produces no change.
(Since cairo 1.10)
-
cairocffi.OPERATOR_HSL_COLOR
Creates a color with the hue and saturation of the source
and the luminosity of the target.
This preserves the gray levels of the target
and is useful for coloring monochrome images or tinting color images.
(Since cairo 1.10)
-
cairocffi.OPERATOR_HSL_LUMINOSITY
Creates a color with the luminosity of the source
and the hue and saturation of the target.
This produces an inverse effect to OPERATOR_HSL_COLOR.
(Since cairo 1.10)
Antialiasing mode
Specifies the type of antialiasing to do when rendering text or shapes.
-
cairocffi.ANTIALIAS_DEFAULT
Use the default antialiasing for the subsystem and target device.
-
cairocffi.ANTIALIAS_NONE
Use a bilevel alpha mask.
-
cairocffi.ANTIALIAS_GRAY
Perform single-color antialiasing.
-
cairocffi.ANTIALIAS_SUBPIXEL
Perform antialiasing by taking advantage of the order
of subpixel elements on devices such as LCD panels.
As it is not necessarily clear from the above what advantages
a particular antialias method provides,
since cairo 1.12, there is also a set of hints:
-
cairocffi.ANTIALIAS_FAST
Allow the backend to degrade raster quality for speed.
-
cairocffi.ANTIALIAS_GOOD
A balance between speed and quality.
-
cairocffi.ANTIALIAS_BEST
A high-fidelity, but potentially slow, raster mode.
These make no guarantee on how the backend will perform its rasterisation
(if it even rasterises!),
nor that they have any differing effect other than to enable
some form of antialiasing.
In the case of glyph rendering,
ANTIALIAS_FAST and ANTIALIAS_GOOD
will be mapped to ANTIALIAS_GRAY,
with ANTIALIAS_BEST being equivalent to ANTIALIAS_SUBPIXEL.
The interpretation of ANTIALIAS_DEFAULT is left entirely up to
the backend, typically this will be similar to ANTIALIAS_GOOD.
Fill rule
Used to select how paths are filled.
For both fill rules, whether or not a point is included in the fill
is determined by taking a ray from that point to infinity
and looking at intersections with the path.
The ray can be in any direction,
as long as it doesn’t pass through the end point of a segment
or have a tricky intersection such as intersecting tangent to the path.
(Note that filling is not actually implemented in this way.
This is just a description of the rule that is applied.)
The default fill rule is FILL_RULE_WINDING.
New entries may be added in future versions.
-
cairocffi.FILL_RULE_WINDING
If the path crosses the ray fromleft-to-right, counts +1.
If the path crosses the rayfrom right to left, counts -1.
(Left and right are determined from the perspective
of looking along the ray from the starting point.)
If the total count is non-zero, the point will be filled.
-
cairocffi.FILL_RULE_EVEN_ODD
Counts the total number of intersections,
without regard to the orientation of the contour.
If the total number of intersections is odd, the point will be filled.
Line cap style
Specifies how to render the endpoints of the path when stroking.
The default line cap style is LINE_CAP_BUTT.
-
cairocffi.LINE_CAP_BUTT
Start (stop) the line exactly at the start (end) point.
-
cairocffi.LINE_CAP_ROUND
Use a round ending, the center of the circle is the end point.
-
cairocffi.LINE_CAP_SQUARE
Use squared ending, the center of the square is the end point.
Line join style
Specifies how to render the junction of two lines when stroking.
The default line join style is LINE_JOIN_MITER.
-
cairocffi.LINE_JOIN_MITER
Use a sharp (angled) corner, see Context.set_miter_limit().
-
cairocffi.LINE_JOIN_ROUND
Use a rounded join, the center of the circle is the joint point.
-
cairocffi.LINE_JOIN_BEVEL
Use a cut-off join, the join is cut off at half the line width
from the joint point.
Font slant
Specifies variants of a font face based on their slant.
-
cairocffi.FONT_SLANT_NORMAL
Upright font style.
-
cairocffi.FONT_SLANT_ITALIC
Italic font style.
-
cairocffi.FONT_SLANT_OBLIQUE
Oblique font style.
Font weight
Specifies variants of a font face based on their weight.
-
cairocffi.FONT_WEIGHT_NORMAL
Normal font weight.
-
cairocffi.FONT_WEIGHT_BOLD
Bold font weight.
Subpixel order
The subpixel order specifies the order of color elements within each pixel
on the display device when rendering with an antialiasing mode of
ANTIALIAS_SUBPIXEL.
-
cairocffi.SUBPIXEL_ORDER_DEFAULT
Use the default subpixel order for for the target device.
-
cairocffi.SUBPIXEL_ORDER_RGB
Subpixel elements are arranged horizontally with red at the left.
-
cairocffi.SUBPIXEL_ORDER_BGR
Subpixel elements are arranged horizontally with blue at the left.
-
cairocffi.SUBPIXEL_ORDER_VRGB
Subpixel elements are arranged vertically with red at the top.
-
cairocffi.SUBPIXEL_ORDER_VBGR
Subpixel elements are arranged vertically with blue at the top.
Hint style
Specifies the type of hinting to do on font outlines.
Hinting is the process of fitting outlines to the pixel grid
in order to improve the appearance of the result.
Since hinting outlines involves distorting them,
it also reduces the faithfulness to the original outline shapes.
Not all of the outline hinting styles are supported by all font backends.
New entries may be added in future versions.
-
cairocffi.HINT_STYLE_DEFAULT
Use the default hint style for font backend and target device.
-
cairocffi.HINT_STYLE_NONE
Do not hint outlines.
-
cairocffi.HINT_STYLE_SLIGHT
Hint outlines slightly to improve contrast
while retaining good fidelity to the original shapes.
-
cairocffi.HINT_STYLE_MEDIUM
Hint outlines with medium strength
giving a compromise between fidelity to the original shapes and contrast.
-
cairocffi.HINT_STYLE_FULL
Hint outlines to maximize contrast.
Metrics hinting mode
Specifies whether to hint font metrics;
hinting font metrics means quantizing them
so that they are integer values in device space.
Doing this improves the consistency of letter and line spacing,
however it also means that text will be laid out differently
at different zoom factors.
-
cairocffi.HINT_METRICS_DEFAULT
Hint metrics in the default manner for the font backend and target device.
-
cairocffi.HINT_METRICS_OFF
Do not hint font metrics.
-
cairocffi.HINT_METRICS_ON
Hint font metrics.
Path operation
Used to describe the type of one portion of a path when represented as a list.
See Context.copy_path() for details.
-
cairocffi.PATH_MOVE_TO
-
cairocffi.PATH_LINE_TO
-
cairocffi.PATH_CURVE_TO
-
cairocffi.PATH_CLOSE_PATH
Pattern extend
Used to describe how pattern color/alpha will be determined
for areas “outside” the pattern’s natural area,
(for example, outside the surface bounds or outside the gradient geometry).
Mesh patterns are not affected by the extend mode.
The default extend mode is
EXTEND_NONE for SurfacePattern
and EXTEND_PAD for Gradient patterns.
New entries may be added in future versions.
-
cairocffi.EXTEND_NONE
Pixels outside of the source pattern are fully transparent.
-
cairocffi.EXTEND_REPEAT
The pattern is tiled by repeating.
-
cairocffi.EXTEND_REFLECT
The pattern is tiled by reflecting at the edges.
-
cairocffi.EXTEND_PAD
Pixels outside of the pattern copy the closest pixel from the source.
Pixel filter
Used to indicate what filtering should be applied
when reading pixel values from patterns.
See Pattern.set_filter() for indicating the desired filter
to be used with a particular pattern.
-
cairocffi.FILTER_FAST
A high-performance filter,
with quality similar to FILTER_NEAREST.
-
cairocffi.FILTER_GOOD
A reasonable-performance filter,
with quality similar to FILTER_BILINEAR.
-
cairocffi.FILTER_BEST
The highest-quality available,
performance may not be suitable for interactive use.
-
cairocffi.FILTER_NEAREST
Nearest-neighbor filtering.
-
cairocffi.FILTER_BILINEAR
Linear interpolation in two dimensions.
-
cairocffi.FILTER_GAUSSIAN
This filter value is currently unimplemented,
and should not be used in current code.
PDF version
Used to describe the version number of the PDF specification
that a generated PDF file will conform to.
-
cairocffi.PDF_VERSION_1_4
The version 1.4 of the PDF specification.
-
cairocffi.PDF_VERSION_1_5
The version 1.5 of the PDF specification.
PostScript level
Used to describe the language level of the PostScript Language Reference
that a generated PostScript file will conform to.
-
cairocffi.PS_LEVEL_2
The language level 2 of the PostScript specification.
-
cairocffi.PS_LEVEL_3
The language level 3 of the PostScript specification.
SVG version
Used to describe the version number of the SVG specification
that a generated SVG file will conform to.
-
cairocffi.SVG_VERSION_1_1
The version 1.1 of the SVG specification.
-
cairocffi.SVG_VERSION_1_2
The version 1.2 of the SVG specification.
Cluster flags
Specifies properties of a text cluster mapping.
Flags are integer values representing a bit field.
-
cairocffi.TEXT_CLUSTER_FLAG_BACKWARD = 0x00000001
The clusters in the cluster array
map to glyphs in the glyph array from end to start. (Since 1.8)