ATS/Cairo Tutorial: | ||
---|---|---|
Prev |
We present a function showtext as follows that draws the text represented by a given string in a manner that puts the center of the drawing at the position (0, 0).
fun showtext{l:agz} ( cr: !cairo_ref l, utf8: string ) : void = () where { var te : cairo_text_extents_t val () = cairo_text_extents (cr, utf8, te) // val width = te.width and height = te.height val x_base = te.width / 2 + te.x_bearing and y_base = ~te.y_bearing / 2 // val (pf0 | ()) = cairo_save (cr) // val () = cairo_rectangle (cr, ~width / 2, ~height/ 2, width, height) val () = cairo_set_source_rgb (cr, 0.5, 0.5, 1.0) val () = cairo_fill (cr) // #define RAD 2.0 val () = cairo_arc (cr, ~x_base, y_base, RAD, 0.0, 2*PI) val () = cairo_set_source_rgb (cr, 1.0, 0.0, 0.0) // red val () = cairo_fill (cr) // val () = cairo_arc (cr, ~x_base+te.x_advance, y_base+te.y_advance, RAD, 0.0, 2*PI) val () = cairo_set_source_rgb (cr, 1.0, 0.0, 0.0) // red val () = cairo_fill (cr) // val () = cairo_move_to (cr, ~x_base, y_base) val () = cairo_text_path (cr, utf8) val () = cairo_set_source_rgb (cr, 0.25, 0.25, 0.25) // dark gray val () = cairo_fill (cr) // val () = cairo_restore (pf0 | cr) // } // end of [showtext]
For instance, the following image is produced by calling showtext (see tutprog_showtext.dats) for the entire code):
Given a string utf8, we can find out some properties about the path that draws the text represented by the string as follows:
The type cairo_text_extents_t is defined as an external struct type in ATS:
// // This external struct type is originally defined in [cairo.h]: // typedef cairo_text_extents_t = $extype_struct "cairo_text_extents_t" of { x_bearing= double , y_bearing= double , width= double , height= double , x_advance= double , y_advance= double } // end of [cairo_text_extents_t]
and the function cairo_text_extents is given the following type:
fun cairo_text_extents{l:agz} ( cr: !cairo_ref l, utf8: string , extents: &cairo_text_extents_t? >> cairo_text_extents_t ) : void // end of [cairo_text_extents]
In the above image depicting the text Top Secret, the center of the left red dot is often referred to as the base point of the text, which initiates the path that draws the text. The width and height of the rectangle forming the background of the text are stored in the fields of width and height of the struct in te, respectively. The vector is (x_bearing, y_bearing) from the base point to the upper left corner of the rectangle, and the vector is (x_advance, y_advance) from the base point to the center of the right red dot, which is the suggested base point for the text that follows.
The function call cairo_text_path(cr, utf8) generates a path that draws the text represented by utf8, where the function cairo_text_path is given the following type in ATS:
Note that a call to cairo_text_path followed by a call to cairo_fill is essentially equivalent to a call to cairo_show_text, which is given the following type in ATS: