gpt4 book ai didi

c# - 将一个字符串换行成多行

转载 作者:IT王子 更新时间:2023-10-29 04:02:17 25 4
gpt4 key购买 nike

我正在尝试将一个字符串换行成多行。每条线都有一个定义的宽度。

例如,如果我将它换行到宽度为 120 像素的区域,我会得到这个结果:

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed augue
velit, tempor non vulputate sit amet,
dictum vitae lacus. In vitae ante
justo, ut accumsan sem. Donec
pulvinar, nisi nec sagittis consequat,
sem orci luctus velit, sed elementum
ligula ante nec neque. Pellentesque
habitant morbi tristique senectus et
netus et malesuada fames ac turpis
egestas. Etiam erat est, pellentesque
eget tincidunt ut, egestas in ante.
Nulla vitae vulputate velit. Proin in
congue neque. Cras rutrum sodales
sapien, ut convallis erat auctor vel.
Duis ultricies pharetra dui, sagittis
varius mauris tristique a. Nam ut
neque id risus tempor hendrerit.
Maecenas ut lacus nunc. Nulla
fermentum ornare rhoncus. Nulla
gravida vestibulum odio, vel commodo
magna condimentum quis. Quisque
sollicitudin blandit mi, non varius
libero lobortis eu. Vestibulum eu
turpis massa, id tincidunt orci.
Curabitur pellentesque urna non risus
adipiscing facilisis. Mauris vel
accumsan purus. Proin quis enim nec
sem tempor vestibulum ac vitae augue.

最佳答案

static void Main(string[] args)
{
List<string> lines = WrapText("Add some text", 300, "Calibri", 11);

foreach (var item in lines)
{
Console.WriteLine(item);
}

Console.ReadLine();
}

static List<string> WrapText(string text, double pixels, string fontFamily,
float emSize)
{
string[] originalLines = text.Split(new string[] { " " },
StringSplitOptions.None);

List<string> wrappedLines = new List<string>();

StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;

foreach (var item in originalLines)
{
FormattedText formatted = new FormattedText(item,
CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface(fontFamily), emSize, Brushes.Black);

actualLine.Append(item + " ");
actualWidth += formatted.Width;

if (actualWidth > pixels)
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
}
}

if(actualLine.Length > 0)
wrappedLines.Add(actualLine.ToString());

return wrappedLines;
}

添加 WindowsBasePresentationCore 库。

关于c# - 将一个字符串换行成多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961278/

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