c - 在开罗使用操作符而不去除背景

标签 c cairo

我只想绘制开罗路径的有限部分,特别是(但不限于)文本。所以我查看了运算符并尝试了 DEST_IN运算符(operator)。

考虑以下示例代码

#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;
}

这是输出的样子:

enter image description here

该运算符可以工作,但不符合预期(即:仅显示所绘制的 50x50 矩形内的文本部分,但背景的其余部分保持不变)。相反,整个背景(除了矩形区域)被删除,并且图片变得透明。

将黑色背景视为任意复杂的绘图。有没有办法根据需要使用操作(从路径中提取范围),而不删除背景的任何部分?

是否有更好的方法来切割路径,以便只绘制提供的矩形内的部分?

最佳答案

开罗如何知道哪一部分是您的“任意复杂绘图”(您想要保留的)和您的蓝色文本(您想要部分删除的)?

这样的事情怎么样? (未经测试!):

#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;
}

关于c - 在开罗使用操作符而不去除背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890424/

相关文章:

c - 如何简化 C 语言中的二进制搜索代码?

c - 我需要在 C 中拆分代码以实现高斯消除法

c - 绑定(bind)失败 : Cannot assign requested address

python - 如何使用 ctypes 将 NumPy 复杂数组与 C 函数连接起来?

c - 如何使用 cairo 绘制左上角和右下角的矩形?

c - 将结构体的地址分配给指针

python - ./waf配置错误pycairo

python - 在 python 中使用 cairosvg 模块时可以指定缩放吗

python-3.x - python pyinstaller 未找到名为 "cairo"的库

user-interface - 如果可能,如何使 Gtk.DrawingArea 在 Gtk.Fixed 容器中可见?