t3r*_*rse 6 c# text system.drawing
我正在开发一个项目,让我近似文本呈现为图像和文本的DHTML编辑器.使用.NET 4 DrawingContext对象的DrawText方法呈现图像.
DrawText方法将文本与字体信息以及尺寸一起使用,并计算使文本尽可能合适所需的包装,如果文本太长则在末尾放置省略号.所以,如果我有以下代码在Rectangle中绘制文本,它将缩写它:
string longText = @"A choice of five engines, although the 2-liter turbo diesel, supposedly good for 48 m.p.g. highway, is not coming to America, at least for now. A 300-horsepower supercharged gasoline engine will likely be the first offered in the United States. All models will use start-stop technology, and fuel consumption will decrease by an average of 19 percent across the A6 lineup. A 245-horsepower A6 hybrid was also unveiled, but no decision has yet been made as to its North America sales prospects. Figure later in 2012, if sufficient demand is detected.";
var drawing = new DrawingGroup();
using (var context = drawing.Open())
{
var text = new FormattedText(longText,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Calibri"),
30,
Brushes.Green);
text.MaxTextHeight = myRect.Height;
text.MaxTextWidth = myRect.Width;
context.DrawText(text, new Point(0, 0));
}
var db = new DrawingBrush(drawing);
db.Stretch = Stretch.None;
myRect.Fill = db;
Run Code Online (Sandbox Code Playgroud)
有没有办法计算文本的包装方式?在这个例子中,输出的文本包裹在"2升"和"48英里/小时"等,如下图所示:

不确定您是否仍然需要解决方案,或者这个特定的解决方案是否适合您的应用程序,但是如果您在块后面插入以下代码片段,using它将显示每行中的文本(因此文本被破坏以进行换行) 。
我使用非常贫民区/游击队的方法得出了这个解决方案,即在调试时浏览属性,寻找包装的文本段 - 我找到了它们,它们位于可访问的属性中......所以你就可以了。很可能有一种更合适/直接的方法。
// Object heirarchy:
// DrawingGroup (whole thing)
// - DrawingGroup (lines)
// - GlyphRunDrawing.GlyphRun.Characters (parts of lines)
// Note, if text is clipped, the ellipsis will be placed in its own
// separate "line" below. Give it a try and you'll see what I mean.
List<DrawingGroup> lines = drawing.Children.OfType<DrawingGroup>().ToList();
foreach (DrawingGroup line in lines)
{
List<char> lineparts = line.Children
.OfType<GlyphRunDrawing>()
.SelectMany(grd => grd.GlyphRun.Characters)
.ToList();
string lineText = new string(lineparts.ToArray());
Debug.WriteLine(lineText);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,嗨大卫。:-)