【问题标题】:How can i add line breaks when rendering Text using X11,如何在使用 X11 渲染文本时添加换行符,
【发布时间】:2017-03-15 02:33:51
【问题描述】:

我正在制作一个应用程序,它使用 X Windows 系统和 Xft 根据屏幕上提到的样式呈现文本。我的代码运行良好,如下所示。

#include <X11/Xlib.h>
#include <X11/Xft/Xft.h>
char * nowShowing() 
{
 return strdup("This is a sample text This is rendered with new Driver installed This is a sample text his is rendered with new Driver installed"); 
}
int main()
{
XftFont *font;
XftDraw *draw;
XRenderColor render_color;
XftColor xft_color;
char *str;
str = nowShowing();
int x = 70;
int y = 150;
Display *dis = XOpenDisplay (0);
int screen = DefaultScreen (dis);
Window  w = XCreateSimpleWindow (dis, RootWindow (dis, screen),
                                 0, 0, 1200, 300, 1,
                                 BlackPixel (dis, screen),
                                 WhitePixel (dis, screen));
XEvent ev;

render_color.red = 0;
render_color.green =0;
render_color.blue = 0;
render_color.alpha = 0xffff;

XftColorAllocValue (dis,
                    DefaultVisual(dis, screen),
                    DefaultColormap(dis, screen),
                    &render_color,
                    &xft_color);

//font = XftFontOpen(dis, screen,
  //                 XFT_FAMILY, XftTypeString, "charter",
  //                 XFT_SIZE, XftTypeDouble, 20.0,
   //                 NULL);
font = XftFontOpenName(dis,screen,"URW Palladio L:style=Bold Italic"); //it takes a Fontconfig pattern string

draw = XftDrawCreate(dis, w,
                     DefaultVisual(dis, screen),
                     DefaultColormap(dis, screen));

XSelectInput (dis, w, ExposureMask);
XMapWindow (dis, w);
for (;;)
{
    XNextEvent (dis, &ev);
    if (ev.type == Expose)
        XftDrawString8(draw, &xft_color, font, x, y, (XftChar8 *) str,
                       strlen(str));
}
return 0;
}

但我想知道如何在输入的文本中添加换行符。我尝试使用“/n”,也尝试制作数组并使用循环,但没有奏效。

【问题讨论】:

  • Idk X11 深入,但通常此类图形系统不像 GUI 工具包的控制台或文本字段那样工作。我很确定您必须在您想要的坐标处分别渲染每一行。 X11 怎么知道文本区域从哪个 X 坐标(假设是水平文本)开始?
  • @Olaf 我们可以用 Xft 定义它应该在新窗口的哪里绘制文本。使用“XftDrawString8”函数左右
  • 你没有明白这一点。您指定要绘制的起点。但这不一定是这条线的起点。 printf("Hello"); printf(" World\nnice thing!"); 的控制台会发生什么?

标签: c x11 freetype2


【解决方案1】:

Xft 不会渲染新行“\n”。您需要根据字体大小和所需的间距分别以适当的偏移量渲染每一行。 我已经修改了代码的结尾块,示例文本在不同的行上呈现了两次。

if (ev.type == Expose)
    {
     int fonth = font->ascent + font->descent;

     XftDrawString8(draw, &xft_color, font, x, y, (XftChar8 *) str,
                   strlen(str));
     XftDrawString8(draw, &xft_color, font, x, y+fonth, (XftChar8 *) str,
                   strlen(str));
    }

【讨论】:

  • 哇哇!好的,我知道这是一些纯文本,我们可以通过更改偏移量以这种方式在不同的行中重复它,但是如果有一个大段落怎么办?当接近窗口宽度时,我将如何告诉 Xft 更改线条。这个评论框的工作方式是一样的吗?
  • Xft 的级别很低,一切都得自己动手。它不是文本格式库,而是文本渲染库。你需要 XGlyphInfo 字形信息;然后调用 XftTextExtentsUtf8(xinfo.dpy, fXFT, (XftChar8 *) str, strlen(str), &glyphinfo);并检查 glyphinfo.width 并将其与窗口宽度进行比较,然后根据需要将字符串拆分为更多行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2020-09-24
相关资源
最近更新 更多