如何使用GTK / Cairo将多个PNG组合成单个PNG

时间:2012-06-11 16:05:35

标签: c animation graphics gtk cairo

我对GTK有点新手,对开罗来说很新。我的任务是创建一个应用程序,需要将PNG作为背景,并将包含字母和数字的多个PNG文件合成到背景PNG上,这样我最终得到一个PNG,然后可以进行转换,旋转,缩放等任何我可能觉得有用的提示,教程,代码示例?与GTK的情况一样,开罗文档似乎缺乏初学者尝试做比绘制形状更复杂的事情。

2 个答案:

答案 0 :(得分:7)

看看这个简单的例子。它只使用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;

}

答案 1 :(得分:4)

谢谢罗德里戈,这是一个非常好的例子!

对于所有 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();