2014-01-17 55 views
1

GTK使用cairo進行繪製。所以我試圖創建一個hello world應用程序,它寫入圖像(svg,png,...)而不是X11。我遇到了兩個問題: - 圖像爲空 - 啓動時沒有運行X11(這是實際的目標),我得到錯誤「**(a.out:9021):警告**:無法打開X顯示「試圖渲染GTK +窗口到圖像

代碼是草稿!

#include <string> 
#include <iostream> 
#include <thread> 
#include <chrono> 
#include <cmath> 

#include <cairo.h> 
#include <cairommconfig.h> 
#include <cairomm/context.h> 
#include <cairomm/surface.h> 
#include <gtk/gtk.h> 
#include <gdk-pixbuf/gdk-pixbuf.h> 

int main(int argc, char *argv[]) 
{ 

    gtk_init(&argc, &argv); 
    GtkWidget *window; 
    GtkWidget *button; 
    // GtkWidget *main_window = gtk_initialize(); 

    window = gtk_offscreen_window_new(); 

    button = gtk_button_new_with_label ("Hello World"); 
    gtk_container_add (GTK_CONTAINER (window), button); 
    gtk_widget_show (window); 
    GdkWindow *gdk_window = gtk_widget_get_window(GTK_WIDGET(window)); 
    std::cout << "gdk window: " << gdk_window << std::endl; 
    cairo_surface_t * surfp = gdk_offscreen_window_get_surface(gdk_window); 
    std::cout << "Created Window will now draw to png" << std::endl; 

    std::string filename = "image.svg"; 
    double width = 600; 
    double height = 400; 

    Cairo::SvgSurface srfobj(surfp); 

    Cairo::RefPtr<Cairo::SvgSurface> refptr(&srfobj); 

    Cairo::RefPtr<Cairo::Context> cr = Cairo::Context::create(refptr); 

    cr->save(); // save the state of the context 
    cr->show_page(); 

    std::cout << "Wrote SVG file \"" << filename << "\"" << std::endl; 
    std::chrono::milliseconds dura(200); 
    std::this_thread::sleep_for(dura); 

    return 0; 
} 
  • 爲什麼不工作的代碼?
  • 我可以在沒有運行X11的情況下運行gtk應用程序,還是應該忽略警告?
+1

可能相關:http://stackoverflow.com/questions/4944441/how-to-draw-any-gtk-widget-on-top-of-cairo-surface – drahnr

回答

1

答案到這兩個問題是,你不能沒有某種形式輸出的運行GTK +應用程序。您正在使用需要XServer的gtk-x11。你可能對DirectFB後端有一些好運,但我不會屏住呼吸,因爲我不知道它是否已經被保存了。

由於Gtk在沒有XServer的情況下運行,因此生成的映像爲空。