如何计算索引在文本框的查看区域中垂直居中的 VerticalOffset? [英] How can I calculate the VerticalOffset at which an index would be vertically centered in the viewing area of a textbox?

查看:19
本文介绍了如何计算索引在文本框的查看区域中垂直居中的 VerticalOffset?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我正在构建的文本编辑器添加查找和替换功能,我希望能够滚动文本框,以便所选匹配项在屏幕上垂直居中.

I am working on adding find and replace functionality to a text editor that I am building and I would like to be able to scroll the textbox so that the selected match is vertically centered on the screen.

推荐答案

您可以使用 GetRectFromCharacterIndex 将字符索引转换为屏幕上的矩形.这将考虑滚动,因此您需要添加当前的 VerticalOffset:

You can use GetRectFromCharacterIndex to convert from a character index to a rectangle on the screen. This will account for scrolling, so you'll need to add the current VerticalOffset:

var start = textBox.GetRectFromCharacterIndex(textBox.SelectionStart);
var end = textBox.GetRectFromCharacterIndex(textBox.SelectionStart + textBox.SelectionLength);
textBox.ScrollToVerticalOffset((start.Top + end.Bottom - textBox.ViewportHeight) / 2 + textBox.VerticalOffset);

如果您有 RichTextBox,则可以使用 TextPointer.GetCharacterRect:

If you have a RichTextBox, you would use TextPointer.GetCharacterRect:

var start = textBox.Selection.Start.GetCharacterRect(LogicalDirection.Forward);
var end = textBox.Selection.End.GetCharacterRect(LogicalDirection.Forward);
textBox.ScrollToVerticalOffset((start.Top + end.Bottom - textBox.ViewportHeight) / 2 + textBox.VerticalOffset);

这篇关于如何计算索引在文本框的查看区域中垂直居中的 VerticalOffset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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