如何围绕多行文本绘制矩形 [英] How to draw a rectangle around multiline text

查看:114
本文介绍了如何围绕多行文本绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iText中围绕多行文字绘制一个矩形。

I am trying to draw a rectangle around multiline text in iText.

用户可以输入一些文本行。文本的字体大小可能不同,可以格式化(粗体,带下划线的...)。

The user will be able to enter some lines of text. The font size of the text might be different and it can be formatted (bold, underlined...).

我使用此代码绘制文本:

I use this code to draw the text:

ColumnText ct = new ColumnText(cb);
Phrase phrase = new Phrase("Some String\nOther string etc...\n test");
ct.setSimpleColumn(myText......);
ct.addElement(phrase);
ct.go();

我知道如何绘制矩形,但我无法绘制一个勾勒此文本的矩形。

I know how to draw a rectangle, but I am not able to draw a rectangle outlining this text.

推荐答案

听起来好像你只缺少一块拼图来满足你的要求。那件作品叫做 getYLine()

It sounds as if you are missing only a single piece of the puzzle to meet your requirement. That piece is called getYLine().

请看一下 DrawRectangleAroundText 示例。此示例两次绘制相同的段落。第一次,它添加了一个看起来像你已经拥有的解决方案的矩形。第二次,它按照您希望的方式添加一个矩形:

Please take a look at the DrawRectangleAroundText example. This example draws the same paragraph twice. The first time, it adds a rectangle that probably looks like the solution you already have. The second time, it adds a rectangle the way you want it to look:

第一次,我们添加如下文字:

The first time, we add the text like this:

ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(120f, 500f, 250f, 780f);
Paragraph p = new Paragraph("This is a long paragraph that doesn't"
        + "fit the width we defined for the simple column of the" 
        + "ColumnText object, so it will be distributed over several"
        + "lines (and we don't know in advance how many).");
ct.addElement(p);
ct.go();

使用坐标定义列:

llx = 120;
lly = 500;
urx = 250;
ury = 780;

这是一个左下角(120,500)的宽度,宽度为130,高度为因此你画一个像这样的矩形:

This is a rectangle with lower left corner (120, 500), a width of 130 and a height of 380. Hence you draw a rectangle like this:

cb.rectangle(120, 500, 130, 280);
cb.stroke();

不幸的是,那个矩形太大了。

Unfortunately, that rectangle is too big.

现在让我们在稍微不同的坐标处再次添加文本:

Now let's add the text once more at slightly different coordinates:

ct = new ColumnText(cb);
ct.setSimpleColumn(300f, 500f, 430f, 780f);
ct.addElement(p);
ct.go();

我们要求<$>而不是使用(300,500)作为矩形的左下角c $ c> ct 使用 getYLine()方法获取当前Y位置的对象:

Instead of using (300, 500) as lower left corner for the rectangle, we ask the ct object for its current Y position using the getYLine() method:

float endPos = ct.getYLine() - 5;

如你所见,我减去5个用户单位,否则我的矩形的底线将与最后一行文字的基线,看起来不太好。现在我可以使用 endPos 值来绘制我的矩形,如下所示:

As you can see, I subtract 5 user units, otherwise the bottom line of my rectangle will coincide with the baseline of the final line of text and that doesn't look very nice. Now I can use the endPos value to draw my rectangle like this:

cb.rectangle(300, endPos, 130, 780 - endPos);
cb.stroke();

这篇关于如何围绕多行文本绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆