文字を書く(Xft編)

概要

Xftを使ってGtk::DrawingAreaに文字を書く

前回と同様に on_expose_event()の中で描画すればよい。

ソース

xdrawstr2.cpp

#include <gtkmm.h>

#include <gdk/gdkx.h>  // GDK_GC_XGC 用
#include <X11/Xft/Xft.h>

class MyDrawArea : public Gtk::DrawingArea
{
    Glib::RefPtr< Gdk::GC > m_gc;
    
public:
    MyDrawArea();

protected:
    virtual bool on_expose_event( GdkEventExpose* e );
};


MyDrawArea::MyDrawArea()
{
    // ダブルバッファリング無効
    set_double_buffered( false );
}


bool MyDrawArea::on_expose_event( GdkEventExpose* event )
{
    if( ! m_gc  ) m_gc = Gdk::GC::create( get_window() );
    int width = get_width();
    int height = get_height();

    GC gc = GDK_GC_XGC( Glib::unwrap( m_gc ) );
    Window win = GDK_DRAWABLE_XID( Glib::unwrap( get_window() ) );
    Display* dpy = GDK_DISPLAY_XDISPLAY( Glib::unwrap( get_window()->get_display() ) );
    Colormap colmap = GDK_COLORMAP_XCOLORMAP( Glib::unwrap( get_default_colormap() ) );

    // 背景の塗りつぶし
    unsigned long fgcolor = BlackPixel( dpy, 0 );
    XSetForeground( dpy, gc, fgcolor );
    XFillRectangle( dpy, win, gc, 0, 0, width, height );

    int scr = DefaultScreen( dpy );
    XftDraw *xftdraw = XftDrawCreate( dpy, win, DefaultVisual( dpy, scr ), colmap );
    if( xftdraw ){

        // フォント作成
        XftFont* font = XftFontOpenName( dpy, scr, "Kochi Gothic-24:style=Regular" );

        // 色設定
        XftColor xftcolor;
        XftColorAllocName( dpy, DefaultVisual( dpy, scr ), colmap, "red", &xftcolor );

        char* msg = "あいうえお" ;
        XftDrawStringUtf8( xftdraw, &xftcolor, font,  20, 100, (FcChar8*)msg, strlen(msg) );

        XftFontClose( dpy, font );
        XftDrawDestroy(xftdraw);
    }

    return true;
}



class MainWin : public Gtk::Window
{
    MyDrawArea m_drawarea;

public:

    MainWin(){
        add( m_drawarea );
        show_all_children();
    }
};



int main( int argc, char *argv[] )
{
    // 無くても良いが一応
    setlocale( LC_ALL, "" );

    Gtk::Main kit( argc, argv );
    MainWin mainwin;
    Gtk::Main::run( mainwin );

    return 0;
}

コンパイル

必要なコンパイルオプションは pkg-config を使って取得する。

g++ xdrawstr2.cpp -o xdrawstr2 `pkg-config gtkmm-2.4 --cflags --libs`

結果