c - 使用 Cairo 旋转和保存 PNG 图像

标签 c graphics 2d cairo

我正在编写一个需要执行以下操作的小型演示应用程序:

  • 阅读引用 PNG图片文件
  • 旋转 PNG图像由 x 度数
  • 将新图像保存为动画帧
  • 最后旋转的结果返回到第 2 步,直到完成旋转。

  • 结果应该是一系列 PNG图像文件以不同程度的旋转显示图像。然后这些图像会以某种方式组合成电影或动画GIF .

    我创建了以下代码尝试进行一次轮换:
    #include <cairo.h>
    #include <math.h>
    
    /**** prototypes *******/
    void Rotate( cairo_surface_t *image, int degress, const char *fileName );
    double DegreesToRadians( double degrees );
    /***********************/
    
    double DegreesToRadians( double degrees )
    {
        return((double)((double)degrees * ( (double)M_PI/(double)180.0 )));
    }
    
    void Rotate( cairo_surface_t *image, int degrees, const char *fileName )
    {
        int w, h;
        cairo_t *cr;
    
        cr = cairo_create(image);
        w = cairo_image_surface_get_width (image);
        h = cairo_image_surface_get_height (image);
    
        cairo_translate(cr, w/2.0, h/2.0);
        cairo_rotate(cr, DegreesToRadians( degrees ));
        cairo_translate(cr, - w/2.0, -h/2.0);
    
        cairo_set_source_surface(cr, image,  0, 0);
        cairo_paint (cr);
    
    
        cairo_surface_write_to_png(image, fileName );
        cairo_surface_destroy (image);
        cairo_destroy(cr);  
    }
    
    int main()
    {
        cairo_surface_t *image = cairo_image_surface_create_from_png ("images/begin.png");
        Rotate(image, 90, "images/end.png");
        return( 0 );
    }
    

    问题是原始图像旋转 90 度后,生成的保存图像旋转但不完全正确。我尝试重新排列 cairo 的顺序所谓的思考可能与表面或上下文的状态有关。

    开始和结束图像如下所示:

    Results

    我错过了什么?

    最佳答案

    您正在打开原始图像作为要绘制的表面。打开您的原始 .png 并通过 cairo_set_source_surface 将其用作源, 并将其绘制到通过 cairo_image_surface_create 创建的新的空图像表面上.

    从替换开始:

    cr = cairo_create(image);
    w = cairo_image_surface_get_width (image);
    h = cairo_image_surface_get_height (image);
    

    和:
    w = cairo_image_surface_get_width (image);
    h = cairo_image_surface_get_height (image);
    cairo_surface_t* tgt = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
    
    cr = cairo_create(tgt);
    

    那么当然,你会想要保存 tgt ,而不是 image ,归档并进行清理。

    关于c - 使用 Cairo 旋转和保存 PNG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11834243/

    相关文章:

    c - memcpy 和二维数组

    android - 在 Android Canvas 上包装长文本

    c - 共享全局变量: interaction between main, lib.a和dll

    c++ - 如果输出是平台字节序,ICONV 写入 BOM 会出现问题

    c++ - 两个物体的蛮力碰撞检测速度太慢

    r - 如何修复 R postscript 函数的剪切输出?

    c++ - 如何聚焦或选择一个项目?

    C++将时间字符串转换为纪元的秒数

    c# - .NET 测试黑白 TIFF 图像而不捕获异常?

    c# - 在 Unity 中转身时翻转敌方 Sprite