如何使用两种不同的字体在GTK标签上显示文字?

时间:2017-06-06 03:50:29

标签: c fonts gtk

我有一个GTK标签,我在Arial Rounded Mt Bold中使用以下代码在其上显示文字:

PangoFontDescription *df;
df = pango_font_description_new ();
pango_font_description_set_family(df,"Arial Rounded Mt Bold");
pango_font_description_set_size(df,fontsize*PANGO_SCALE);
gtk_widget_modify_font(Message_Label, df);
gtk_label_set_text(GTK_LABEL(Label), "Hello World");
pango_font_description_free (df);

现在此Hello World显示在Arial Rounded Mt Bold中。但是,如果我想在Arial Rounded Mt Bold中显示Hello,在其他字体中显示例如Arial。这是否可以在GTK标签中使用。我在C中这样做。任何建议或任何有用的链接。感谢。

1 个答案:

答案 0 :(得分:5)

gtk_widget_modify_font()已被弃用,并且不会让您按照自己的意愿行事。

您可以使用PangoAttrList,它将属性(包括PangoFontDescriptor的各个组件)组合在文本范围内。例如:

PangoAttrList *attrlist;
PangoAttribute *attr;
PangoFontDescription *df;

attrlist = pango_attr_list_new();

// First, let's set up the base attributes.
// This part is copied from your code (and slightly bugfixed and reformatted):
df = pango_font_description_new();
pango_font_description_set_family(df, "Arial Rounded MT");
pango_font_description_set_size(df, fontsize * PANGO_SCALE);
pango_font_description_set_weight(df, PANGO_WEIGHT_BOLD);
// You can also use pango_font_description_new_from_string() and pass in a string like "Arial Rounded MT Bold (whatever fontsize is)".
// But here's where things change:
attr = pango_attr_font_desc_new(df);
// This is not documented, but pango_attr_font_desc_new() makes a copy of df, so let's release ours:
pango_font_description_free(df);
// Pango and GTK+ use UTF-8, so our string is indexed between 0 and 11.
// Note that the end_index is exclusive!
attr->start_index = 0;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);
// And pango_attr_list_insert() takes ownership of attr, so we don't free it ourselves.
// As an alternative to all that, you can have each component of the PangoFontDescriptor be its own attribute; see the PangoAttribute documentation page.

// And now the attribute for the word "World".
attr = pango_attr_family_new("Arial");
// "World" starts at 6 and ends at 11.
attr->start_index = 6;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);

// And finally, give the GtkLabel our attribute list.
gtk_label_set_attributes(GTK_LABEL(Label), attrlist);
// And (IIRC this is not documented either) gtk_label_set_attributes() takes a reference on the attribute list, so we can remove ours.
pango_attr_list_unref(attrlist);

您还可以使用gtk_label_set_markup()use an HTML-like markup language一次性设置文字和样式:

gtk_label_set_markup(GTK_LABEL(Label),
    "<span face=\"Arial Rounded MT\" size=\"(whatever fontsize * PANGO_SCALE is)\" weight=\"bold\">Hello <span face=\"Arial\">World</span></span>");
// Or even...
gtk_label_set_markup(GTK_LABEL(Label),
    "<span font=\"Arial Rounded MT Bold (whatever fontsize is)\">Hello <span face=\"Arial\">World</span></span>");