0

Using Cairo under C++ on a Raspberry Pi, and trying to clip text drawing to inside a given rectangle.
I'd have thought that it would be as simple as this:

cairo_t* cp = cairo_create(psurface);
// set font, etc
cairo_rectangle(cp, 0, 0, 100, 100); // Desired clipping rect
cairo_clip(cp);
cairo_show_text(cp, "pretend that this string is > 100px wide");
cairo_destroy(cp);

but it always causes no text to appear. If I omit the call to cairo_clip() the text does appear (albeit unclipped).
I'm wanting only the last few chars of the string to get clipped.
What's the trick?

dlchambers
  • 3,511
  • 3
  • 29
  • 34

1 Answers1

1

Works for me.

enter image description here

#include <cairo.h>

int main()
{
    cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 150, 50);
    cairo_t *cr = cairo_create(s);

    cairo_set_source_rgb(cr, 1, 0, 0);
    cairo_paint(cr);

    cairo_rectangle(cr, 0, 0, 100, 100);
    cairo_clip(cr);
    cairo_move_to(cr, 50, 25);
    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_show_text(cr, "pretend that this string is > 100px wide");

    cairo_destroy(cr);
    cairo_surface_write_to_png(s, "out.png");
    cairo_surface_destroy(s);

    return 0;
}
Uli Schlachter
  • 9,337
  • 1
  • 23
  • 39
  • The relevant item is calling cairo_move_to() **AFTER** calling cairo_clip(). Turns out that my code WAS drawing & clipping, but because I was calling cairo_move_to() **BEFORE** calling cairo_rectangle() and cairo_clip() this caused cairo_show_text(), which references the baseline, to draw the text at the top of the rect. Calling cairo_move_to() just before cairo_show_text() solved it. – dlchambers Oct 25 '18 at 13:44