gpt4 book ai didi

python - 如何在 svgwrite 中实现文本换行?

转载 作者:行者123 更新时间:2023-12-04 11:43:49 46 4
gpt4 key购买 nike

我在 python 中使用 svgwrite 根据我的 Tensorflow 模型生成输出以输出模拟手写文本。我当前的设置需要一个字符串数组来表示换行符,但是生成的文本大小不一致,有时会在行中的最后一个单词之后呈现尴尬的间距,例如
this
是否可以将文本换行添加到单个长行中,当当前行达到给定的最大宽度时会自动添加换行符? Google 搜索将我带到 svgwrite 页面并建议使用 TextArea但给出的例子是 HTML。

    def _draw(self, strokes, lines, filename, stroke_colors=None, \
stroke_widths=None, background_color='white'):

lines = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit,",
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris",
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in",
"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
]

stroke_colors = stroke_colors or ['black']*len(lines)
stroke_widths = stroke_widths or [2]*len(lines)

line_height = 35
view_width = 152.4
view_height = 101.6

dwg = svgwrite.Drawing(filename=filename)
dwg.viewbox(width=view_width, height=view_height)
dwg.add(dwg.rect(insert=(0, 0), size=('153mm', '102mm'), fill=background_color))

for i in range(3):


initial_coord = np.array([30,-((i*450)+25)])
strokesc = self._sample(lines, [1 for i in lines], [7 for i in lines]);

for offsets, line, color, width in zip(strokesc, lines, stroke_colors, stroke_widths):

if not line:
initial_coord[1] -= line_height
continue
offsets[:, :2] *= random.randint(150, 190)/100
strokesc = drawing.offsets_to_coords(offsets)
strokesc = drawing.denoise(strokesc)
strokesc[:, :2] = drawing.align(strokesc[:, :2])

strokesc[:, 1] *= -1
strokesc[:, :2] -= strokesc[:, :2].min() + initial_coord

prev_eos = 1.0
p = "M{},{} ".format(0, 0)
for x, y, eos in zip(*strokesc.T):
p += '{}{},{} '.format('M' if prev_eos == 1.0 else 'L', x, y)
prev_eos = eos
path = svgwrite.path.Path(p)
path = path.stroke(color=color, width=width, linecap='round').fill("none")
dwg.add(path)

initial_coord[1] -= line_height

dwg.save()
这是我当前在 python 中的解决方案,它输出上面的示例

最佳答案

您可以尝试直接处理文本:

my_text = sum(lines)
nb_lines = len(lines)


nb_words_per_line = len(my_text.split()) // nb_lines

new_lines = []
cmpt = 0
tmp = ""
for i, word in enumerate(my_text.split()):

if cmpt%nb_words_per_line == 0:
new_lines.append(tmp)
tmp = ""
tmp += word + " "

if tmp:
new_lines.append(tmp)

然后您可以使用 new_lines如您所用 lines前。

关于python - 如何在 svgwrite 中实现文本换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68138815/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com