我对GTK有点陌生,对开罗也很陌生。我的任务是创建一个应用程序,该应用程序需要将 PNG 作为背景,并将包含字母和数字的多个 PNG 文件合成到背景 PNG 上,以便我最终得到一个 PNG,然后可以转换、旋转、缩放等。我可能会觉得有用的任何提示、教程和代码示例?与GTK的情况一样,对于试图做比绘制形状更复杂的事情的初学者来说,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;
}
谢谢罗德里戈,这是一个很好的例子!
对于所有 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();