gpt4 book ai didi

c# - WPF richTextBox问题

转载 作者:太空狗 更新时间:2023-10-29 21:48:17 25 4
gpt4 key购买 nike

如果一行文本换行到另一行,我如何以编程方式确定字符串中断开的点。

示例:输入字符串 =“这是对换行文本的测试”。

      Based on the width of the richTextBox it could display:


This is a test of a wrapped line of
text.

我需要确定的是被换行的单词在行中的偏移量。在上面的例子中是“文本”这个词。

当我从 richTextBox 中提取 Xaml 时,我得到了展开的原始文本。

谢谢,

鲍勃克林格

最佳答案

我发现的技巧是使用 TextPointer 类及其 GetCharacterRec 方法。

RichTextBox 包含一个 FlowDocument。流文档中的文本包含在 Run 对象中(有点简化,但它有效)。代码在第一次运行开始时找到 TextPointer。然后它获取第一个字符的边界矩形。接下来代码一次向前走一个字符,得到一个新的边界矩形并检查新矩形的底部是否与原始矩形不同。如果底部不同,那么我们就换了一条线。然后 TextPointer 可以在中断之前或之后获取文本。

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void inspect(object sender, RoutedEventArgs e)
{
TextPointer pointer = FindRun(inBox.Document);

string textAfterBreak = FindBreak(pointer);

outBox.Text = textAfterBreak;
}

private string FindBreak(TextPointer pointer)
{
Rect rectAtStart = pointer.GetCharacterRect(LogicalDirection.Forward);

pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
Rect currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);

while (currentRect.Bottom == rectAtStart.Bottom)
{
pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
}

string textBeforeBreak = pointer.GetTextInRun(LogicalDirection.Backward);
string textAfterBreak = pointer.GetTextInRun(LogicalDirection.Forward);

return textAfterBreak;
}

private TextPointer FindRun(FlowDocument document)
{
TextPointer position = document.ContentStart;

while (position != null)
{
if (position.Parent is Run)
break;

position = position.GetNextContextPosition(LogicalDirection.Forward);
}

return position;
}
}

<Window x:Class="LineBreaker.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<RichTextBox Grid.Row="0" Name="inBox">
</RichTextBox>
<Button Grid.Row="1" Click="inspect">Find Break</Button>
<TextBox Name="outBox" Grid.Row="2"/>
</Grid>
</Window>

关于c# - WPF richTextBox问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/306679/

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