R – Finding width of characters to do wordwrap


I'm writing a custom texteditor using WPF and am using a stack of TextBlocks to render the lines. That leads me to the problem to find when to wordwrap from one line to the next.

What is the best way to do this? Is there a way to find the width of each characther/glyph (other than creating a FormatedText class for each character)?

Best Solution

I had to do this in order to solve this problem. Maybe you could check out the code there. The relevant part of the code is:

var textPointer = run.ContentStart;
textPointer = textPointer.GetPositionAtOffset(start, LogicalDirection.Forward);
var leftRectangle = textPointer.GetCharacterRect(LogicalDirection.Forward);
textPointer = textPointer.GetPositionAtOffset(length, LogicalDirection.Forward);
var rightRectangle = textPointer.GetCharacterRect(LogicalDirection.Backward);
var rect = new Rect(leftRectangle.TopLeft, rightRectangle.BottomRight);
var translatedPoint = uiHost.TranslatePoint(new Point(0, 0), null);
rect.Offset(translatedPoint.X, translatedPoint.Y);
Related Question