gtk字体渲染使用本机Windows句柄

时间:2014-02-16 11:34:07

标签: cairo gtk2 pango

我使用gtk + 2创建了一个用于渲染文本的小gui应用程序。在win32上处理可怕的字体。我正在使用本机窗口句柄(HDC)创建一个cairo表面。现在,在Windows中字体看起来很漂亮,但看起来画布在绘制操作后没有正确更新,除非我调整窗口大小。这只发生在win32上。

下面的代码在linux和win32上编译

#include <iostream>
#include <gtk/gtk.h>
#include <unistd.h>

#ifdef WIN32
#include <cairo-win32.h>
#include <gdk/gdkwin32.h>
#include <pango/pangowin32.h>
#include <windows.h>
#endif

using namespace std;

GtkWidget* drgArea;
GtkWidget* window;

int x = 0;
int y = 0;
string text = "click on this window";

void on_mouse_down(GtkWidget *widget, GdkEventButton *event, gpointer data) {
    x = event->x;
    y = event->y;
    gtk_widget_queue_draw(drgArea);
}

gboolean on_draw(GtkWidget *widget, GdkEventExpose *event, gpointer data) {
    cout << "on_draw=" << widget << endl;

    cairo_t* cr;
    PangoLayout* layout;
    PangoContext* pangoContext;
    GdkGC* gc;

#ifdef CAIRO_HAS_WIN32_SURFACE
    gc = gdk_gc_new(widget->window);
    HDC hdc = gdk_win32_hdc_get(widget->window, gc, GDK_GC_SUBWINDOW);
    cairo_surface_t* cairo_win_surf;
    cairo_win_surf = cairo_win32_surface_create (hdc);
    cr = cairo_create(cairo_win_surf);

#else
    cr = gdk_cairo_create(widget->window);
#endif

    pangoContext = pango_cairo_create_context(cr);
    layout = pango_layout_new(pangoContext);
    pango_layout_set_text(layout, (const char*) text.c_str(), text.size());
    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_move_to(cr, x, y);
    pango_cairo_show_layout(cr, layout);
    cairo_destroy(cr);

#ifdef CAIRO_HAS_WIN32_SURFACE
    gdk_win32_hdc_release(widget->window, gc, GDK_GC_SUBWINDOW);
#endif

    return TRUE;
}

int main(int argc, char** argv) {
    cout << "**** main ****" << endl;

    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    drgArea = gtk_drawing_area_new();
    gtk_widget_set_events(drgArea,
            GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK
                    | GDK_BUTTON_RELEASE_MASK);

    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_widget_set_size_request(window, 400, 300);
    gtk_container_add(GTK_CONTAINER(window), drgArea);
    gtk_widget_show_all(window);

    g_signal_connect(drgArea, "button-press-event", G_CALLBACK(on_mouse_down),
            NULL);
    g_signal_connect(drgArea, "expose-event", G_CALLBACK(on_draw), NULL);

    gtk_main();
    return 0;
}

我也在寻找您认为合适的其他建议。

1 个答案:

答案 0 :(得分:0)

我发现必须将解决方案窗口双缓冲设置为

https://people.gnome.org/~federico/misc/gtk-drawing-model/