我只想绘制cairo路径的有限部分,尤其是(但不限于)文本。所以我查看了运算符并尝试了DEST_IN运算符。
考虑以下示例代码
#include <cairo/cairo.h>
int main (int argc, char *argv[])
{
cairo_surface_t *surface =
cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 300, 300);
cairo_t *cr = cairo_create (surface);
//black background
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_paint(cr);
//blue text
cairo_set_source_rgb(cr, 0, 0, 1);
cairo_set_font_size(cr, 50);
cairo_move_to(cr, 75, 160);
cairo_text_path(cr, "foobar");
cairo_fill(cr);
//this should remove all parts of the blue text that
//is not in the following rectangle
cairo_set_operator(cr, CAIRO_OPERATOR_DEST_IN);
cairo_rectangle(cr, 125, 125, 50, 50);
cairo_fill(cr);
cairo_destroy (cr);
cairo_surface_write_to_png (surface, "output.png");
cairo_surface_destroy (surface);
return 0;
}
这是输出的外观:
操作符可以正常工作,但不符合预期(即:仅显示绘制的50x50矩形内的文本部分,但背景的其余部分未被触及)。相反,整个背景(矩形区域除外)被删除,图片变得透明。
将黑色背景视为任意复杂的绘图。有没有办法根据需要使用该操作(从路径中提取范围),而不删除背景的任何部分?
是否有更好的方法来剪切路径,因此只绘制所提供矩形内的部分?
答案 0 :(得分:1)
cairo如何知道哪部分是你的“任意复杂绘图”(你想保留)和你的蓝色文字(你想要部分删除)?
这样的事情怎么样? (未测试!):
#include <cairo/cairo.h>
int main (int argc, char *argv[])
{
cairo_surface_t *surface =
cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 300, 300);
cairo_t *cr = cairo_create (surface);
//black background
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_paint(cr);
// Redirect drawing to a temporary surface
cairo_push_group(cr);
//blue text
cairo_set_source_rgb(cr, 0, 0, 1);
cairo_set_font_size(cr, 50);
cairo_move_to(cr, 75, 160);
cairo_text_path(cr, "foobar");
cairo_fill(cr);
// Draw part of the blue text
cairo_pop_group_to_source(cr);
cairo_rectangle(cr, 125, 125, 50, 50);
cairo_fill(cr);
cairo_destroy (cr);
cairo_surface_write_to_png (surface, "output.png");
cairo_surface_destroy (surface);
return 0;
}