【发布时间】:2021-08-15 12:54:31
【问题描述】:
我想在一个使用 Gtkmm 的应用程序中用 Cairo 绘制一个简单的文本。我想在单击Gtk::FontButton 时(换句话说,当signal_font_set 信号发出时)直接给出字体样式(可以是Pango::FontDescription 或Pango::Context 等等...)以使用Cairo 绘制文本)。在下面的示例中,我有一个Gtk::HeaderBar,其中包含一个Gtk::FontButton,它在单击时将Glib::RefPtr<<Pango::Context>> 发送到绘图类。我想要这样的东西:
MyWindow.cpp:
#include <iostream>
#include "MyWindow.h"
MyWindow::MyWindow() {
set_default_size(1000, 1000);
set_position(Gtk::WIN_POS_CENTER);
header.set_show_close_button(true);
header.pack_start(fontButton);;
set_titlebar(header);
fontButton.signal_font_set().connect([&] {
drawingArea.select_font(fontButton.get_pango_context());
});
scrolledWindow.add(drawingArea);
add(scrolledWindow);
show_all();
}
MyDrawing.h:
#ifndef DRAWING_H
#define DRAWING_H
#include <gtkmm.h>
#include <cairo/cairo.h>
class MyDrawing : public Gtk::Layout
{
public:
MyDrawing();
~MyDrawing() override;
void select_font(Glib::RefPtr<Pango::Context> p_pangoContext);
private:
bool draw_text(const Cairo::RefPtr<::Cairo::Context>& p_context);
Glib::RefPtr<Pango::Context> m_pangoContext;
};
#endif // DRAWING_H
和MyDrawing.cpp:
#include <iostream>
#include <utility>
#include "MyDrawing.h"
#include <cairomm/context.h>
#include <cairomm/surface.h>
MyDrawing::MyDrawing() {
this->signal_draw().connect(sigc::mem_fun(*this, &MyDrawing::draw_text));
}
MyDrawing::~MyDrawing() = default;
bool MyDrawing::draw_text(const Cairo::RefPtr<::Cairo::Context> &p_context) {
auto layout = create_pango_layout("hello ");
if(m_pangoContext) {
layout->set_font_description(m_pangoContext->get_font_description());
}
else {
Pango::FontDescription fontDescription;
layout->set_font_description(fontDescription);
}
p_context->save();
p_context->set_font_size(30);
p_context->set_source_rgb(0.1, 0.1, 0.1);
p_context->move_to(40, 40);
layout->show_in_cairo_context(p_context);
p_context->restore();
return true;
}
void MyDrawing::select_font(Glib::RefPtr<Pango::Context> p_pangoContext) {
this->m_pangoContext = std::move(p_pangoContext);
queue_draw();
}
当我手动设置Pango::FontDescription 时:
Pango::FontDescription fontDescription;
fontDescription.set_weight(Pango::WEIGHT_BOLD);
fontDescription.set_style(Pango::STYLE_ITALIC);
layout->set_font_description(fontDescription);
有效:
【问题讨论】:
-
如果我正确理解您的问题,您是否希望在
MyDrawing::draw_text中设置字体描述?我认为这不是工作代码? -
我编辑了帖子。
-
更清楚了,谢谢!另外,如果有更多代码(请尝试使其下次可重现),我可以在这里重现该问题。