使用生成的图像作为开罗图形中的图案

Use generated image as pattern inside cairo graphics

我已经使用模式浏览了 cairo 图形示例。

pattern = cairo_pattern_create_for_surface (image);
cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT);

现在我有一个表面序列为:-

而不是 "image"
cairo_move_to(cr, xc[0], yc[0]);
    for (int i = 0; i < xc.size(); i++)
        cairo_line_to(cr, xc[i], yc[i]);

如何使用生成的 cairo 表面并将其用作图案的输入? 如果我只是使用它是行不通的 pattern = cairo_pattern_create_for_surface (surface); 其中 surface 有 cairo_t cr.

It does not work if I simply use pattern = cairo_pattern_create_for_surface (surface); where surface has the cairo_t cr.

是的,确实如此。

以下代码在 10x10 的表面上画了一个十字,然后用它填充 20x20 的表面。

#include <cairo.h>

int main()
{
    cairo_surface_t *pattern_surface = cairo_image_surface_create(
            CAIRO_FORMAT_ARGB32, 10, 10);
    cairo_surface_t *result_surface = cairo_image_surface_create(
            CAIRO_FORMAT_ARGB32, 20, 20);
    cairo_t *cr;
    cairo_pattern_t *pattern;

    cr = cairo_create(pattern_surface);
    cairo_move_to(cr, 0, 0);
    cairo_line_to(cr, 10, 10);
    cairo_move_to(cr, 10, 0);
    cairo_line_to(cr, 0, 10);
    cairo_stroke(cr);
    cairo_destroy(cr);

    pattern = cairo_pattern_create_for_surface(pattern_surface);
    cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT);

    cr = cairo_create(result_surface);
    cairo_set_source(cr, pattern);
    cairo_paint(cr);
    cairo_destroy(cr);

    cairo_surface_write_to_png(result_surface, "out.png");

    cairo_surface_destroy(pattern_surface);
    cairo_surface_destroy(result_surface);
    cairo_pattern_destroy(pattern);
    return 0;
}