我正在研究一個項目,該項目使我近似渲染爲文本的圖像和DHTML編輯器的文本。圖像使用.NET 4 DrawingContext對象的DrawText方法呈現。在.NET DrawingContext中計算文本環繞DrawText方法
DrawText方法會將文本和字體信息以及尺寸一起取出並計算必要的包裝以使文本儘可能合適,如果文本太長,則在末尾放置省略號。所以,如果我有以下的代碼來繪製一個矩形文本會abbrevaiate它:
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;
有沒有一種方法來計算文本將如何包裝?在這個例子中,輸出的文本被包裝成「2升」和「48 m.p.g」等,如下圖所示:
Graphics.MeasureString *不是*替代TextRenderer.MeasureText()。 – 2011-01-20 01:22:59
+1 Hans。實際上,這個問題的根源在於,使用上述技術的代碼幾乎是定期不準確的。 – t3rse 2011-01-20 13:50:04