强制GtkLabel裁剪其居中对齐的文本 [英] Force GtkLabel to clip its center-aligned text
问题描述
我有一个GtkLabel
,其文本将保持居中,而不论其短于或长于标签.
I`ve got a GtkLabel
whose text is to remain centered regardless of whether it is shorter or longer than the label.
例如,设置了SS_CENTER
样式标志的Win32静态控件的行为如下:
For example, a Win32 static control that has the SS_CENTER
style flag set behaves like that:
┌===========================┐
│ Lorem ipsum dolor │
└===========================┘
-当文本短于控件时;
— when the text is shorter than the control;
┌===========================┐
Lorem ipsum│dolor sit amet, consectetur│adipiscing
└===========================┘
-文本长于控件时.
N.B.:用户看到的文本的唯一部分是在框架内.
N.B.: The only part of the text seen by the user is inside the frame.
我希望GtkLabel
-s做同样的事情,但实际上它们以不同的方式呈现居中文本:
I expected GtkLabel
-s to do the same thing, but actually they render centered text differently:
┌===========================┐
│ Lorem ipsum dolor │
└===========================┘
-文本短于控件时;
┌===========================┐
│Lorem ipsum dolor sit amet,│consectetur adipiscing
└===========================┘
-文本长于控件时.
我如何使GtkLabel
中的居中文本即使居长也仍居中?
How do I make centered text in a GtkLabel
remain centered even when it is long?
以防万一:用户看到的实际文本以〜4 FPS更新,并且在运行时之前未知.
Just in case: the actual text the user sees is updated at ~4 FPS and is unknown prior to runtime.
推荐答案
终于解决了.
#include <gtk/gtk.h>
struct SCTX {
GtkWidget *text;
GdkRectangle rect;
};
void Resize(GtkWidget *view, GdkRectangle *rect, gpointer user) {
struct SCTX *sctx = user;
GtkRequisition requ;
if ((sctx->rect.width != rect->width )
|| (sctx->rect.height != rect->height)) {
sctx->rect = *rect;
gtk_widget_size_request(sctx->text, &requ);
gtk_layout_move(view, sctx->text, (rect->width - requ.width ) / 2,
(rect->height - requ.height) / 2);
}
}
int main(int argc, char *argv[]) {
GtkWidget *hwnd, *view;
struct SCTX sctx = {0};
gtk_init(&argc, &argv);
hwnd = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(hwnd, "destroy", gtk_main_quit, 0);
view = gtk_layout_new(0, 0);
g_signal_connect(view, "size-allocate", G_CALLBACK(Resize), &sctx);
gtk_widget_set_size_request(view, 320, 200);
sctx.text = gtk_label_new("Lorem ipsum dolor sit amet, consectetur "
"adipiscing elit, sed do eiusmod tempor "
"incididunt ut labore et dolore magna aliqua");
gtk_container_add(view, sctx.text);
gtk_container_add(hwnd, view);
gtk_container_set_border_width(GTK_CONTAINER(hwnd), 32);
gtk_window_set_position(GTK_WINDOW(hwnd), GTK_WIN_POS_CENTER);
gtk_widget_show_all(hwnd);
gtk_main();
return 0;
}
这里的关键部分是将GtkLayout
包裹在我们的GtkLabel
周围,以便前者可以将后者移动到其范围之内.
The crucial part here is wrapping a GtkLayout
around our GtkLabel
so the former could move the latter around inside its bounds.
这篇关于强制GtkLabel裁剪其居中对齐的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!