如何使用GTK/Cairo将多个PNG合成为一个单独的PNG?

3

我对GTK有一些了解,但对Cairo非常陌生。我被委托创建一个应用程序,需要将PNG作为背景,并将包含字母和数字的多个PNG文件合成到背景PNG中,以便最终得到一个单独的PNG,然后可以进行变换、旋转、缩放等操作。请问有什么提示、教程或代码示例对我有用吗?与GTK一样,对于试图做一些比绘制形状更复杂的事情的初学者来说,Cairo文档似乎有些不足。

2个回答

9

看一下这个简单的例子。它只使用了cairo:

#include <cairo.h>

int main()
{
    //Load a few images from files
    cairo_surface_t *surf1 = cairo_image_surface_create_from_png("a.png");
    cairo_surface_t *surf2 = cairo_image_surface_create_from_png("b.png");

    //Create the background image
    cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 100, 100);

    //Create the cairo context
    cairo_t *cr = cairo_create(img);

    //Initialize the image to black transparent
    cairo_set_source_rgba(cr, 0,0,0, 1);
    cairo_paint(cr);

    //Paint one image
    cairo_set_source_surface(cr, surf1, 0, 0);
    cairo_paint(cr);

    //Paint the other image
    cairo_set_source_surface(cr, surf2, 50, 50);
    cairo_paint(cr);

    //Destroy the cairo context and/or flush the destination image
    cairo_surface_flush(img);
    cairo_destroy(cr);

    //And write the results into a new file
    cairo_surface_write_to_png(img, "result.png");

    //Be tidy and collect your trash
    cairo_surface_destroy(img);
    cairo_surface_destroy(surf1);
    cairo_surface_destroy(surf2);

    return 0;

}

4
感谢Rodrigo,这是一个很好的例子!对于所有C#程序员,下面是完全相同的示例翻译为C#。我只在SetSourceRGBA()中做了一个小改变-允许使用透明背景图像而不是黑色:
Using Cairo;

    //Load a few images from files
    ImageSurface surf1 = new ImageSurface("a.png");
    ImageSurface surf2 = new ImageSurface("b.png");

    //Create the background image
    ImageSurface img = new ImageSurface(Format.Argb32, 200, 200);

    //Create the cairo context
    Context cr = new Context(img);

    //Initialize the image to black transparent
    // cr.SetSourceRGBA(255,255,255,1); // This will create the background image with white background
    // cr.SetSourceRGBA(0,0,0,1);       // This will create the background image with black background
    cr.SetSourceRGBA(0,0,0,0);          // This creates the background image with transparent background
    cr.Paint ();


    //Paint one image
    cr.SetSourceSurface(surf1,0,0);
    cr.Paint();

    //Paint the other image
    cr.SetSourceSurface(surf2, 25, 50);
    cr.Paint();

    //Destroy the cairo context and/or flush the destination image
    img.Flush();

    //And write the results into a new file
    img.WriteToPng("result.png");

    //Be tidy and collect your trash
    img.Dispose();
    img.Destroy();
    surf1.Destroy ();
    surf2.Destroy();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接