Module Cairo

Cairo: A Vector Graphics Library (bindings).

Drawing:

Fonts:

Surfaces (platform independent Surface backends and others):

Surfaces that Cairo supports but for which no OCaml binding has been created (yet, please contribute!):

In order to get acquainted with Cairo's concepts we recommend that you read the Cairo OCaml tutorial.

type status =
  1. | INVALID_RESTORE
  2. | INVALID_POP_GROUP
  3. | NO_CURRENT_POINT
  4. | INVALID_MATRIX
  5. | INVALID_STATUS
  6. | NULL_POINTER
  7. | INVALID_STRING
  8. | INVALID_PATH_DATA
  9. | READ_ERROR
  10. | WRITE_ERROR
  11. | SURFACE_FINISHED
  12. | SURFACE_TYPE_MISMATCH
  13. | PATTERN_TYPE_MISMATCH
  14. | INVALID_CONTENT
  15. | INVALID_FORMAT
  16. | INVALID_VISUAL
  17. | FILE_NOT_FOUND
  18. | INVALID_DASH
  19. | INVALID_DSC_COMMENT
  20. | INVALID_INDEX
  21. | CLIP_NOT_REPRESENTABLE
  22. | TEMP_FILE_ERROR
  23. | INVALID_STRIDE
  24. | FONT_TYPE_MISMATCH
  25. | USER_FONT_IMMUTABLE
  26. | USER_FONT_ERROR
  27. | NEGATIVE_COUNT
  28. | INVALID_CLUSTERS
  29. | INVALID_SLANT
  30. | INVALID_WEIGHT
  31. | INVALID_SIZE
  32. | USER_FONT_NOT_IMPLEMENTED
  33. | DEVICE_TYPE_MISMATCH
  34. | DEVICE_ERROR
  35. | INVALID_MESH_CONSTRUCTION
  36. | DEVICE_FINISHED
  37. | JBIG2_GLOBAL_MISSING
exception Error of status

Error status: raised by functions of this module to indicate a cause of failure.

val status_to_string : status -> string

Provides a human-readable description of a status.

exception Unavailable

Exception raised by functions of backend modules when they are not available in the installed Cairo library.

type context

The cairo drawing context. This is the main object used when drawing with cairo. To draw with cairo, you create a Surface.t, create a context from it and create shapes with functions such as Cairo.move_to and Cairo.line_to, and then actually draw them with Cairo.stroke or Cairo.fill.

Generic matrix operations

type matrix = {
  1. mutable xx : float;
  2. mutable yx : float;
  3. mutable xy : float;
  4. mutable yy : float;
  5. mutable x0 : float;
  6. mutable y0 : float;
}

Holds an affine transformation, such as a scale, rotation, shear, or a combination of those. The transformation of a point (x, y) is given by:

x_new = xx *. x +. xy *. y +. x0;
y_new = yx *. x +. yy *. y +. y0;
module Matrix : sig ... end

This is used throughout cairo to convert between different coordinate spaces.

Rendering text and glyphs

type text_extents = {
  1. x_bearing : float;
    (*

    The horizontal distance from the origin of the text to the leftmost part of the glyphs as drawn. Positive if the glyphs lie entirely to the right of the origin.

    *)
  2. y_bearing : float;
    (*

    The vertical distance from the origin to the topmost part of the glyphs as drawn. Positive only if the glyphs lie completely below the origin; will usually be negative.

    *)
  3. width : float;
    (*

    width of the glyphs as drawn

    *)
  4. height : float;
    (*

    height of the glyphs as drawn

    *)
  5. x_advance : float;
    (*

    Distance to advance in the X direction after drawing these glyphs.

    *)
  6. y_advance : float;
    (*

    Distance to advance in the Y direction after drawing these glyphs. Will typically be zero except for vertical text layout as found in East-Asian languages.

    *)
}

The Cairo.text_extents structure stores the extents of a single glyph or a string of glyphs in user-space coordinates. Because text extents are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call Cairo.scalecr 2.0 2.0, text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged.

Low-level text API

module Glyph : sig ... end

This is Cairo low-level text API. The low-level API relies on the user to convert text to a set of glyph indexes and positions. This is a very hard problem and is best handled by external libraries, like the pangocairo that is part of the Pango text layout and rendering library. Pango is available from http://www.pango.org/

"Toy" text API

This is cairo's toy text API. The toy API takes UTF-8 encoded text and is limited in its functionality to rendering simple left-to-right text with no advanced features. That means for example that most complex scripts like Hebrew, Arabic, and Indic scripts are out of question. No kerning or correct positioning of diacritical marks either. The font selection is pretty limited too and doesn't handle the case that the selected font does not cover the characters in the text. This set of functions are really that, a toy text API, for testing and demonstration purposes. Any serious application should avoid them.

See the Glyph module for the low-level text API.

type antialias =
  1. | ANTIALIAS_DEFAULT
    (*

    Use the default antialiasing for the subsystem and target device

    *)
  2. | ANTIALIAS_NONE
    (*

    Use a bilevel alpha mask

    *)
  3. | ANTIALIAS_GRAY
    (*

    Perform single-color antialiasing (using shades of gray for black text on a white background, for example).

    *)
  4. | ANTIALIAS_SUBPIXEL
    (*

    Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels

    *)

Specifies the type of antialiasing to do when rendering text or shapes.

type subpixel_order =
  1. | SUBPIXEL_ORDER_DEFAULT
    (*

    Use the default subpixel order for for the target device

    *)
  2. | SUBPIXEL_ORDER_RGB
    (*

    Subpixel elements are arranged horizontally with red at the left

    *)
  3. | SUBPIXEL_ORDER_BGR
    (*

    Subpixel elements are arranged horizontally with blue at the left

    *)
  4. | SUBPIXEL_ORDER_VRGB
    (*

    Subpixel elements are arranged vertically with red at the top

    *)
  5. | SUBPIXEL_ORDER_VBGR
    (*

    Subpixel elements are arranged vertically with blue at the top

    *)

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 (see Cairo.antialias).

type hint_style =
  1. | HINT_STYLE_DEFAULT
    (*

    Use the default hint style for font backend and target device

    *)
  2. | HINT_STYLE_NONE
    (*

    Do not hint outlines

    *)
  3. | HINT_STYLE_SLIGHT
    (*

    Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.

    *)
  4. | HINT_STYLE_MEDIUM
    (*

    Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast.

    *)
  5. | HINT_STYLE_FULL
    (*

    Hint outlines to maximize contrast.

    *)

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.

type hint_metrics =
  1. | HINT_METRICS_DEFAULT
    (*

    Hint metrics in the default manner for the font backend and target device.

    *)
  2. | HINT_METRICS_OFF
    (*

    Do not hint font metrics.

    *)
  3. | HINT_METRICS_ON
    (*

    Hint font metrics.

    *)

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.

module Font_options : sig ... end

The font options specify how fonts should be rendered. Most of the time the font options implied by a surface are just right and do not need any changes, but for pixel-based targets tweaking font options may result in superior output on a particular display.

type slant =
  1. | Upright
  2. | Italic
  3. | Oblique

Specifies variants of a font face based on their slant.

type weight =
  1. | Normal
  2. | Bold

Specifies variants of a font face based on their weight.

type font_type = [
  1. | `Toy
    (*

    The font was created using cairo's toy font api

    *)
  2. | `Ft
    (*

    The font is of type FreeType

    *)
  3. | `Win32
    (*

    The font is of type Win32

    *)
  4. | `Quartz
    (*

    The font is of type Quartz

    *)
  5. | `User
    (*

    The font was create using cairo's user font api

    *)
]

Cairo.font_type is used to describe the type of a given font face or scaled font. The font types are also known as "font backends" within cairo.

The type of a font face is determined by the function used to create it, which will generally be of the form Cairo.*.font_face_create. The font face type can be queried with Cairo.Font_face.get_type

The various Cairo.Font_face functions can be used with a font face of any type.

The type of a scaled font is determined by the type of the font face passed to Cairo.Scaled_font.create. The scaled font type can be queried with Cairo.Scaled_font.get_type.

The various Cairo.Scaled_font functions can be used with scaled fonts of any type, but some font backends also provide type-specific functions (such as Cairo.Ft.scaled_font_lock_face) that must only be called with a scaled font of the appropriate type.

FIXME: The behavior of calling a type-specific function with a scaled font of the wrong type is undefined.

module Font_face : sig ... end

Cairo.Font_face.t represents a particular font at a particular weight, slant, and other characteristic but no size, transformation, or size.

type font_extents = {
  1. ascent : float;
    (*

    the distance that the font extends above the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements above it.

    *)
  2. descent : float;
    (*

    the distance that the font extends below the baseline. This value is positive for typical fonts that include portions below the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the the font should align with elements below it.

    *)
  3. baseline : float;
    (*

    the recommended vertical distance between baselines when setting consecutive lines of text with the font. This is greater than ascent+descent by a quantity known as the line spacing or external leading. When space is at a premium, most fonts can be set with only a distance of ascent+descent between lines.

    *)
  4. max_x_advance : float;
    (*

    the maximum distance in the X direction that the the origin is advanced for any glyph in the font.

    *)
  5. max_y_advance : float;
    (*

    the maximum distance in the Y direction that the the origin is advanced for any glyph in the font. this will be zero for normal fonts used for horizontal writing. (The scripts of East Asia are sometimes written vertically.)

    *)
}

The Cairo.font_extents structure stores metric information for a font. Values are given in the current user-space coordinate system.

Because font metrics are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call Cairo.scalecr 2.0 2.0, text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged.

module Scaled_font : sig ... end

Cairo.Scaled_font.t represents a realization of a font face at a particular size and transformation and a certain set of font options.

module Ft : sig ... end

A minimal Interface to FreeType/Fontconfig. Functions in this module will raie Unavailable if Cairo has not been compiled with FreeType support (and fonconfig is available). This module is not thread safe.

val select_font_face : context -> ?slant:slant -> ?weight:weight -> string -> unit

select_font_face cr family ?slant ?weight selects a family and style of font from a simplified description as a family name, slant and weight. Cairo provides no operation to list available family names on the system (this is a "toy", remember), but the standard CSS2 generic family names, ("serif", "sans-serif", "cursive", "fantasy", "monospace"), are likely to work as expected.

  • parameter slant

    default Upright.

  • parameter weight

    default Normal.

    For "real" font selection, see the font-backend-specific font_face_create functions for the font backend you are using. (For example, if you are using the freetype-based cairo-ft font backend, see Cairo.Ft.create_for_ft_face or Cairo.Ft.create_for_pattern.) The resulting font face could then be used with Cairo.Scaled_font.create and Cairo.Scaled_font.set.

    Similarly, when using the "real" font support, you can call directly into the underlying font system (such as fontconfig or freetype), for operations such as listing available fonts, etc.

    It is expected that most applications will need to use a more comprehensive font handling and text layout library (for example, pango) in conjunction with cairo.

    If text is drawn without a call to Cairo.select_font_face, (nor Cairo.Font_face.set nor Cairo.Scaled_font.set), the default family is platform-specific, but is essentially "sans-serif". Default slant is Upright, and default weight is Normal.

val set_font_size : context -> float -> unit

set_font_size cr size sets the current font matrix to a scale by a factor of size, replacing any font matrix previously set with set_font_size or Cairo.set_font_matrix. This results in a font size of size user space units. (More precisely, this matrix will result in the font's em-square being a size by size square in user space.)

If text is drawn without a call to set_font_size (nor Cairo.set_font_matrix, nor Cairo.Scaled_font.set), the default font size is 10.0.

val set_font_matrix : context -> Matrix.t -> unit

set_font_matrix cr matrix sets the current font matrix to matrix. The font matrix gives a transformation from the design space of the font (in this space, the em-square is 1 unit by 1 unit) to user space. Normally, a simple scale is used (see Cairo.set_font_size), but a more complex font matrix can be used to shear the font or stretch it unequally along the two axes.

val get_font_matrix : context -> Matrix.t

Returns the current font matrix. See Cairo.set_font_matrix.

val show_text : context -> string -> unit

A drawing operator that generates the shape from a string of UTF-8 characters, rendered according to the current font_face, font_size (font_matrix), and font_options.

This function first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph.

After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for easy display of a single logical string with multiple calls to show_text.

val font_extents : context -> font_extents

Gets the font extents for the currently selected font.

val text_extents : context -> string -> text_extents

text_extents cr utf8 gets 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 Cairo.show_text). Additionally, the x_advance and y_advance values indicate the amount by which the current point would be advanced by Cairo.show_text.

Note that whitespace characters do not directly contribute to the size of the rectangle (extents.width and extents.height). They do contribute indirectly by changing the position of non-whitespace characters. In particular, trailing whitespace characters are likely to not affect the size of the rectangle, though they will affect the x_advance and y_advance values.

Surfaces

type rectangle = {
  1. x : float;
    (*

    X coordinate of the left side of the rectangle

    *)
  2. y : float;
    (*

    Y coordinate of the the top side of the rectangle

    *)
  3. w : float;
    (*

    width of the rectangle

    *)
  4. h : float;
    (*

    height of the rectangle

    *)
}

A data structure for holding a rectangle.

Base module for surfaces

type content =
  1. | COLOR
  2. | ALPHA
  3. | COLOR_ALPHA

This is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

module Surface : sig ... end

Abstract representation of all different drawing targets that cairo can render to; the actual drawings are performed using a cairo context.

Surface backends

Below are the surface backends that do not depend of a particular platform. XLib, Win32, and Quartz are defined in their own modules.

module Image : sig ... end

Image surfaces provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in Cairo.Image.format.

module PDF : sig ... end

The PDF surface is used to render cairo graphics to Adobe PDF files and is a multi-page vector surface backend.

module PNG : sig ... end

The PNG functions allow reading PNG images into image surfaces, and writing any surface to a PNG file.

module PS : sig ... end

The PostScript surface is used to render cairo graphics to Adobe PostScript files and is a multi-page vector surface backend.

module SVG : sig ... end

The SVG surface is used to render cairo graphics to SVG files and is a multi-page vector surface backend.

module Recording : sig ... end

The recording surface is a surface that records all drawing operations at the highest level of the surface backend interface. The surface can then be "replayed" against any target surface by using it as a source surface.

Sources for drawing

module Pattern : sig ... end

Paint (and also mask and brush) with which cairo draws and associated function.

The cairo drawing context functions

val create : Surface.t -> context

create target creates a new context with all graphics state parameters set to default values and with target as a target surface. The target surface should be constructed with a backend-specific function such as Cairo.Image.create (or any other Backend.create variant). For many backends, you should not forget to call Cairo.Surface.finish for the data to be completely outputted.

  • raises Out_of_memory

    if the context could not be allocated.

val save : context -> unit

save cr makes a copy of the current state of cr and saves it on an internal stack of saved states for cr. When restore is called, cr will be restored to the saved state. Multiple calls to save and restore can be nested; each call to restore restores the state from the matching paired save.

val restore : context -> unit

restore cr restores cr to the state saved by a preceding call to save and removes that state from the stack of saved states.

val get_target : context -> Surface.t

Gets the target surface for the cairo context as passed to create.

module Group : sig ... end

Temporary redirection of drawing commands to intermediate surfaces.

val set_source_rgb : context -> float -> float -> float -> unit

set_source_rgb cr r g b sets the source pattern within cr to an opaque color. This opaque color will then be used for any subsequent drawing operation until a new source pattern is set.

The color components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

The default source pattern is opaque black (that is, it is equivalent to set_source_rgb cr 0. 0. 0.).

val set_source_rgba : context -> float -> float -> float -> float -> unit

set_source_rgba cr r g b a sets the source pattern within cr to a translucent color. This color will then be used for any subsequent drawing operation until a new source pattern is set.

The color and alpha components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

The default source pattern is opaque black (that is, it is equivalent to set_source_rgba cr 0. 0. 0. 1.0).

val set_source : context -> 'a Pattern.t -> unit

set_source cr source sets the source pattern within cr to source. This pattern will then be used for any subsequent drawing operation until a new source pattern is set.

Note: The pattern's transformation matrix will be locked to the user space in effect at the time of set_source. This means that further modifications of the current transformation matrix will not affect the source pattern. See Pattern.set_matrix.

The default source pattern is a solid pattern that is opaque black (that is, it is equivalent to set_source_rgb cr 0. 0. 0.).

val set_source_surface : context -> Surface.t -> x:float -> y:float -> unit

set_source_surface cr surface x y is a convenience for creating a pattern from surface and setting it as the source in cr with set_source.

The x and y parameters give the user-space coordinate at which the surface origin should appear. (The surface origin is its upper-left corner before any transformation has been applied.) The x and y patterns are negated and then set as translation values in the pattern matrix.

Other than the initial translation pattern matrix, as described above, all other pattern attributes (such as its extend mode) are set to the default values as in Pattern.create_for_surface. The resulting pattern can be queried with Cairo.get_source so that these attributes can be modified if desired (e.g. to create a repeating pattern with Cairo.Pattern.set_extend).

val get_source : context -> Pattern.any

get_source cr gets the current source pattern for cr.

val set_antialias : context -> antialias -> unit

Set the antialiasing mode of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, no backend supports ANTIALIAS_SUBPIXEL when drawing shapes.

Note that this option does not affect text rendering, instead see Cairo.Font_options.set_antialias.

val get_antialias : context -> antialias

Gets the current shape antialiasing mode, as set by Cairo.set_antialias.

val set_dash : context -> ?ofs:float -> float array -> unit

set_dash cr dashes sets the dash pattern to be used by Cairo.stroke. A dash pattern is specified by dashes, an array of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. The offset ofs specifies an offset into the pattern at which the stroke begins (default: 0.).

set_dash [| |] disable dashing. set_dash [|l|] sets a symmetric pattern with alternating on and off portions of the size l.

Each "on" segment will have caps applied as if the segment were a separate sub-path. In particular, it is valid to use an "on" length of 0.0 with Cairo.line_cap being ROUND or SQUARE in order to distributed dots or squares along a path.

Note: The length values are in user-space units as evaluated at the time of stroking. This is not necessarily the same as the user space at the time of set_dash.

val get_dash : context -> float array * float

Gets the current dash array (( [| |], 0.) if dashing is not currently in effect).

type fill_rule =
  1. | WINDING
    (*

    If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from 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.

    *)
  2. | 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.

    *)

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 WINDING.

val set_fill_rule : context -> fill_rule -> unit

set_fill_rule cr fill_rule sets the current fill rule within the cairo context cr. The fill rule is used to determine which regions are inside or outside a complex (potentially self-intersecting) path. The current fill rule affects both Cairo.fill and Cairo.clip. See Cairo.fill_rule for details on the semantics of each available fill rule.

val get_fill_rule : context -> fill_rule

Gets the current fill rule, as set by set_fill_rule.

type line_cap =
  1. | BUTT
    (*

    start(stop) the line exactly at the start(end) point

    *)
  2. | ROUND
    (*

    use a round ending, the center of the circle is the end point

    *)
  3. | SQUARE
    (*

    use squared ending, the center of the square is the end point

    *)

Specifies how to render the endpoints of the path when stroking. The default line cap style is BUTT.

val set_line_cap : context -> line_cap -> unit

set_line_cap cr line_cap sets the current line cap style within the cairo context cr. See Cairo.line_cap for details about how the available line cap styles are drawn.

As with the other stroke parameters, the current line cap style is examined by Cairo.stroke, Cairo.stroke_extents, and Cairo.stroke_to_path, but does not have any effect during path construction.

The default line cap style is BUTT.

val get_line_cap : context -> line_cap

Gets the current line cap style, as set by Cairo.set_line_cap.

type line_join =
  1. | JOIN_MITER
    (*

    use a sharp (angled) corner, see Cairo.set_miter_limit

    *)
  2. | JOIN_ROUND
    (*

    use a rounded join, the center of the circle is the joint point

    *)
  3. | JOIN_BEVEL
    (*

    use a cut-off join, the join is cut off at half the line width from the joint point

    *)

Specifies how to render the junction of two lines when stroking. The default line join style is MITER.

val set_line_join : context -> line_join -> unit

Sets the current line join style within the cairo context. See Cairo.line_join for details about how the available line join styles are drawn.

As with the other stroke parameters, the current line join style is examined by Cairo.stroke, Cairo.stroke_extents, and Cairo.stroke_to_path, but does not have any effect during path construction.

The default line join style is MITER.

val get_line_join : context -> line_join

Gets the current line join style, as set by Cairo.set_line_join.

val set_line_width : context -> float -> unit

Sets the current line width within the cairo context. The line width value specifies the diameter of a pen that is circular in user space (though device-space pen may be an ellipse in general due to scaling/shear/rotation of the CTM).

Note: When the description above refers to user space and CTM it refers to the user space and CTM in effect at the time of the stroking operation, not the user space and CTM in effect at the time of the call to set_line_width. The simplest usage makes both of these spaces identical. That is, if there is no change to the CTM between a call to set_line_with and the stroking operation, then one can just pass user-space values to set_line_width and ignore this note.

As with the other stroke parameters, the current line width is examined by Cairo.stroke, Cairo.stroke_extents, and Cairo.stroke_to_path, but does not have any effect during path construction.

The default line width value is 2.0.

val get_line_width : context -> float

This function returns the current line width value exactly as set by Cairo.set_line_width. Note that the value is unchanged even if the CTM has changed between the calls to set_line_width and get_line_width.

val set_miter_limit : context -> float -> unit

Sets the current miter limit within the cairo context.

If the current line join style is set to MITER (see Cairo.set_line_join), the miter limit is used to determine whether the lines should be joined with a bevel instead of a miter. Cairo divides the length of the miter by the line width. If the result is greater than the miter limit, the style is converted to a bevel.

As with the other stroke parameters, the current line miter limit is examined by Cairo.stroke, Cairo.stroke_extents, and Cairo.stroke_to_path, but does not have any effect during path construction.

The default miter limit value is 10.0, which will convert joins with interior angles less than 11 degrees to bevels instead of miters. For reference, a miter limit of 2.0 makes the miter cutoff at 60 degrees, and a miter limit of 1.414 makes the cutoff at 90 degrees.

A miter limit for a desired angle can be computed as: miter limit = 1/sin(angle/2).

val get_miter_limit : context -> float

Gets the current miter limit, as set by Cairo.set_miter_limit.

Drawing operations

type operator =
  1. | CLEAR
    (*

    clear destination layer (bounded)

    *)
  2. | SOURCE
    (*

    replace destination layer (bounded)

    *)
  3. | OVER
    (*

    draw source layer on top of destination layer (bounded)

    *)
  4. | IN
    (*

    draw source where there was destination content (unbounded)

    *)
  5. | OUT
    (*

    draw source where there was no destination content (unbounded)

    *)
  6. | ATOP
    (*

    draw source on top of destination content and only there

    *)
  7. | DEST
    (*

    ignore the source

    *)
  8. | DEST_OVER
    (*

    draw destination on top of source

    *)
  9. | DEST_IN
    (*

    leave destination only where there was source content (unbounded)

    *)
  10. | DEST_OUT
    (*

    leave destination only where there was no source content

    *)
  11. | DEST_ATOP
    (*

    leave destination on top of source content and only there (unbounded)

    *)
  12. | XOR
    (*

    source and destination are shown where there is only one of them

    *)
  13. | ADD
    (*

    source and destination layers are accumulated

    *)
  14. | SATURATE
    (*

    like over, but assuming source and dest are disjoint geometries

    *)

Compositing operator for all cairo drawing operations.

The default operator is Cairo.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/

val set_operator : context -> operator -> unit

Sets the compositing operator to be used for all drawing operations. See Cairo.operator for details on the semantics of each available compositing operator.

The default operator is OVER.

val get_operator : context -> operator

Gets the current compositing operator for a cairo context.

val set_tolerance : context -> float -> unit

Sets the tolerance used when converting paths into trapezoids. Curved segments of the path will be subdivided until the maximum deviation between the original path and the polygonal approximation is less than tolerance. The default value is 0.1. A larger value will give better performance, a smaller value, better appearance. (Reducing the value from the default value of 0.1 is unlikely to improve appearance significantly.)

val get_tolerance : context -> float

Gets the current tolerance value, as set by Cairo.set_tolerance.

val clip : context -> unit

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Cairo.fill and according to the current fill rule (see Cairo.set_fill_rule).

After clip, the current path will be cleared from the cairo context.

Calling Cairo.clip can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling Cairo.clip within a Cairo.save / Cairo.restore pair. The only other means of increasing the size of the clip region is Cairo.clip_reset.

val clip_preserve : context -> unit

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Cairo.fill and according to the current fill rule (see Cairo.set_fill_rule).

Unlike Cairo.clip, preserves the path within the cairo context.

Calling Cairo.clip_preserve can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling Cairo.clip_preserve within a Cairo.save / Cairo.restore pair. The only other means of increasing the size of the clip region is Cairo.clip_reset.

val clip_extents : context -> rectangle

Computes a bounding box in user coordinates covering the area inside the current clip.

val clip_reset : context -> unit

Reset the current clip region to its original, unrestricted state. That is, set the clip region to an infinitely large shape containing the target surface. Equivalently, if infinity is too hard to grasp, one can imagine the clip region being reset to the exact bounds of the target surface.

Note that code meant to be reusable should not call clip_reset as it will cause results unexpected by higher-level code which calls Cairo.clip. Consider using Cairo.save and Cairo.restore around Cairo.clip as a more robust means of temporarily restricting the clip region.

(This function binds Cairo cairo_reset_clip.)

val clip_rectangle_list : context -> rectangle list

Gets the current clip region as a list of rectangles in user coordinates.

Raises Error(CLIP_NOT_REPRESENTABLE) to indicate that the clip region cannot be represented as a list of user-space rectangles.

val fill : context -> unit

A drawing operator that fills the current path according to the current fill rule (each sub-path is implicitly closed before being filled). After fill, the current path will be cleared from the cairo context.

See also Cairo.set_fill_rule.

val fill_preserve : context -> unit

A drawing operator that fills the current path according to the current fill rule (each sub-path is implicitly closed before being filled). Unlike Cairo.fill, fill_preserve preserves the path within the cairo context.

See also Cairo.set_fill_rule.

val fill_extents : context -> rectangle

Computes a bounding box in user coordinates covering the area that would be affected (the "inked" area) by a fill operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle { x=0.; y=0.; w=0.; h=0. }. Surface dimensions and clipping are not taken into account.

Contrast with Cairo.Path.extents, which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment).

Note that fill_extents must necessarily do more work to compute the precise inked areas in light of the fill rule, so Cairo.Path.extents may be more desirable for sake of performance if the non-inked path extents are desired.

See Cairo.fill and Cairo.set_fill_rule.

val in_fill : context -> float -> float -> bool

Tests whether the given point is inside the area that would be affected by a fill operation given the current path and filling parameters. Surface dimensions and clipping are not taken into account.

See also Cairo.fill and Cairo.set_fill_rule.

val mask : context -> 'a Pattern.t -> unit

mask cr pattern: a drawing operator that paints the current source using the alpha channel of pattern as a mask. (Opaque areas of pattern are painted with the source, transparent areas are not painted.)

val mask_surface : context -> Surface.t -> x:float -> y:float -> unit

mask_surface cr surface x y: a drawing operator that paints the current source using the alpha channel of surface as a mask. (Opaque areas of surface are painted with the source, transparent areas are not painted.)

  • parameter x

    X coordinate at which to place the origin of surface.

  • parameter y

    Y coordinate at which to place the origin of surface.

val paint : ?alpha:float -> context -> unit

A drawing operator that paints the current source everywhere within the current clip region. If alpha is set, the drawing is faded out using the alpha value.

  • parameter alpha

    alpha value, between 0 (transparent) and 1 (opaque).

val stroke : context -> unit

A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. After stroke, the current path will be cleared from the cairo context. See Cairo.set_line_width, Cairo.set_line_join, Cairo.set_line_cap, and Cairo.set_dash.

Note: Degenerate segments and sub-paths are treated specially and provide a useful result. These can result in two different situations:

1. Zero-length "on" segments set in Cairo.set_dash. If the cap style is ROUND or SQUARE then these segments will be drawn as circular dots or squares respectively. In the case of SQUARE, the orientation of the squares is determined by the direction of the underlying path.

2. A sub-path created by Cairo.move_to followed by either a Cairo.Path.close or one or more calls to Cairo.line_to to the same coordinate as the Cairo.move_to. If the cap style is ROUND then these sub-paths will be drawn as circular dots. Note that in the case of SQUARE line cap, a degenerate sub-path will not be drawn at all (since the correct orientation is indeterminate).

In no case will a cap style of BUTT cause anything to be drawn in the case of either degenerate segments or sub-paths.

val stroke_preserve : context -> unit

Like Cairo.stroke except that it preserves the path within the cairo context.

val stroke_extents : context -> rectangle

Computes a bounding box in user coordinates covering the area that would be affected (the "inked" area) by a Cairo.stroke operation operation given the current path and stroke parameters. If the current path is empty, returns an empty rectangle { x=0.; y=0.; w=0.; h=0. }. Surface dimensions and clipping are not taken into account.

Note that if the line width is set to exactly zero, then stroke_extents will return an empty rectangle. Contrast with Cairo.Path.extents which can be used to compute the non-empty bounds as the line width approaches zero.

Note that stroke_extents must necessarily do more work to compute the precise inked areas in light of the stroke parameters, so Cairo.Path.extents may be more desirable for sake of performance if non-inked path extents are desired.

See Cairo.stroke, Cairo.set_line_width, Cairo.set_line_join, Cairo.set_line_cap, and Cairo.set_dash.

val in_stroke : context -> float -> float -> bool

Tests whether the given point is inside the area that would be affected by a Cairo.stroke operation given the current path and stroking parameters. Surface dimensions and clipping are not taken into account.

val copy_page : context -> unit

copy_page cr emits the current page for backends that support multiple pages, but doesn't clear it, so, the contents of the current page will be retained for the next page too. Use Cairo.show_page if you want to get an empty page after the emission.

This is a convenience function that simply calls Cairo.Surface.copy_page on cr's target.

val show_page : context -> unit

show_page cr emits and clears the current page for backends that support multiple pages. Use Cairo.copy_page if you don't want to clear the page.

This is a convenience function that simply calls Cairo.Surface.show_page on cr's target.

Creating paths and manipulating path data

Paths are the most basic drawing tools and are primarily used to implicitly generate simple masks.

type path_data =
  1. | MOVE_TO of float * float
  2. | LINE_TO of float * float
  3. | CURVE_TO of float * float * float * float * float * float
  4. | CLOSE_PATH
module Path : sig ... end
val arc : context -> float -> float -> r:float -> a1:float -> a2:float -> unit

arc xc yc radius angle1 angle2 adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*PI until it is greater than angle1.

If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling Cairo.Path.sub before calling arc.

Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of π/2 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction.

(To convert from degrees to radians, use degrees * (π / 180.).)

This function gives the arc in the direction of increasing angles; see Cairo.arc_negative to get the arc in the direction of decreasing angles.

The arc is circular in user space. To achieve an elliptical arc, you can scale the current transformation matrix by different amounts in the X and Y directions. For example, to draw an ellipse in the box given by x, y, width, height (we suppose pi holds the value of π):

open Cairo

save cr;
translate cr (x +. width /. 2.) (y +. height /. 2.);
scale cr (width /. 2.) (height /. 2.);
arc cr 0. 0. 1. 0. (2 * pi);
restore cr;
val arc_negative : context -> float -> float -> r:float -> a1:float -> a2:float -> unit

arc_negative xc yc radius angle1 angle2 adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*PI until it is less than angle1.

See Cairo.arc for more details. This function differs only in the direction of the arc between the two angles.

val curve_to : context -> float -> float -> float -> float -> float -> float -> unit

curve_to ctx x1 y1 x2 y2 x3 y3 Adds a cubic Bézier spline to the path from the current point to position (x3, y3) in user-space coordinates, using (x1, y1) and (x2, y2) as the control points. After this call the current point will be (x3, y3).

If there is no current point before the call to curve_to this function will behave as if preceded by a call to Cairo.move_to cr x1 y1.

val line_to : context -> float -> float -> unit

Adds a line to the path from the current point to position (x, y) in user-space coordinates. After this call the current point will be (x, y).

If there is no current point before the call to Cairo.line_to, this function will behave as Cairo.move_to cr x y.

val move_to : context -> float -> float -> unit

Begin a new sub-path. After this call the current point will be (x, y).

val rectangle : context -> float -> float -> w:float -> h:float -> unit

rectangle x y w h adds a closed sub-path rectangle of the given size to the current path at position (x, y) in user-space coordinates.

This function is logically equivalent to:

move_to cr x y;
rel_line_to cr width 0;
rel_line_to cr 0 height;
rel_line_to cr (-. width) 0;
Path.close cr;
val rel_curve_to : context -> float -> float -> float -> float -> float -> float -> unit

rel_curve_to x1 y1 x2 y2 x3 y3 relative-coordinate version of Cairo.curve_to. All offsets are relative to the current point. Adds a cubic Bézier spline to the path from the current point to a point offset from the current point by (dx3, dy3), using points offset by (dx1, dy1) and (dx2, dy2) as the control points. After this call the current point will be offset by (dx3, dy3).

Given a current point of (x, y), rel_curve_to cr dx1 dy1 dx2 dy2 dx3 dy3 is logically equivalent to curve_to cr (x+.dx1) (y+.dy1) (x+.dx2) (y+.dy2) (x+.dx3) (y+.dy3).

It is an error to call this function with no current point. Doing so will cause Error NO_CURRENT_POINT to be raised.

val rel_line_to : context -> float -> float -> unit

Relative-coordinate version of Cairo.line_to. Adds a line to the path from the current point to a point that is offset from the current point by (dx, dy) in user space. After this call the current point will be offset by (dx, dy).

Given a current point of (x, y), rel_line_to cr dx dy is logically equivalent to line_to cr (x +. dx) (y +. dy).

It is an error to call this function with no current point. Doing so will cause Error NO_CURRENT_POINT to be raised.

val rel_move_to : context -> float -> float -> unit

Begin a new sub-path. After this call the current point will offset by (x, y).

Given a current point of (x, y), rel_move_to cr dx dy is logically equivalent to move_to cr (x +. dx) (y +. dy).

It is an error to call this function with no current point. Doing so will cause Error NO_CURRENT_POINT to be raised.

Manipulating the current transformation matrix

The current transformation matrix, ctm, is a two-dimensional affine transformation that maps all coordinates and other drawing instruments from the user space into the surface's canonical coordinate system, also known as the device space.

See also Cairo.Matrix.

val translate : context -> float -> float -> unit

translate cr tx ty modifies the current transformation matrix (CTM) by translating the user-space origin by (tx, ty). This offset is interpreted as a user-space coordinate according to the CTM in place before the new call to translate. In other words, the translation of the user-space origin takes place after any existing transformation.

val scale : context -> float -> float -> unit

scale sx sy modifies the current transformation matrix (CTM) by scaling the X and Y user-space axes by sx and sy respectively. The scaling of the axes takes place after any existing transformation of user space.

val rotate : context -> float -> unit

rotate ctx angle modifies the current transformation matrix (CTM) by rotating the user-space axes by angle radians. The rotation of the axes takes places after any existing transformation of user space. The rotation direction for positive angles is from the positive X axis toward the positive Y axis.

val transform : context -> Matrix.t -> unit

transform cr matrix modifies the current transformation matrix (CTM) by applying matrix as an additional transformation. The new transformation of user space takes place after any existing transformation.

val set_matrix : context -> Matrix.t -> unit

set_matrix cr matrix Modifies the current transformation matrix (CTM) by setting it equal to matrix.

val get_matrix : context -> Matrix.t

Return the current transformation matrix (CTM).

val identity_matrix : context -> unit

Resets the current transformation matrix (CTM) by setting it equal to the identity matrix. That is, the user-space and device-space axes will be aligned and one user-space unit will transform to one device-space unit.

val user_to_device : context -> float -> float -> float * float

user_to_device cr x y transform a coordinate from user space to device space by multiplying the given point by the current transformation matrix (CTM).

val user_to_device_distance : context -> float -> float -> float * float

user_to_device_distance cr dx dy transform a distance vector from user space to device space. This function is similar to Cairo.user_to_device except that the translation components of the CTM will be ignored when transforming (dx,dy).

val device_to_user : context -> float -> float -> float * float

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

val device_to_user_distance : context -> float -> float -> float * float

device_to_user_distance cr dx dy transform a distance vector from device space to user space. This function is similar to Cairo.device_to_user except that the translation components of the inverse CTM will be ignored when transforming (dx,dy).