2016-03-13 74 views
11

在WPF中,這是可能的使用FormattedText,像這樣:如何測量UWP應用程序中的文本大小?

private Size MeasureString(string candidate) 
{ 
    var formattedText = new FormattedText(
     candidate, 
     CultureInfo.CurrentUICulture, 
     FlowDirection.LeftToRight, 
     new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch), 
     this.textBlock.FontSize, 
     Brushes.Black); 

    return new Size(formattedText.Width, formattedText.Height); 
} 

但UWP此類不存在了。那麼如何計算通用Windows平臺的文本尺寸?

回答

23

在UWP,創建TextBlock,設置其屬性(如TextFontSize),然後調用其Measure方法和通過在無限大。

var tb = new TextBlock { Text = "Text", FontSize = 10 }; 
tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); 

之後,其DesiredSize屬性包含TextBlock將具有的大小。

+5

@Reddy我沒那麼快(雖然我希望我是)。提問時有一個「回答你自己的問題」複選框。我這樣做是因爲我沒有發現任何問題或對這個問題的答案,以便其他人會發現它(希望),而不必搜索它的時間。 – Domysee

+3

請注意,這不是特定於UWP的。它也適用於WPF或Silverlight。 – Clemens

+0

@MarcelW不知道你的意思。這對我來說也很好,在WPF中也是如此。 – Clemens

0

下面是使用Win2D一種替代方法:

private Size MeasureTextSize(string text, CanvasTextFormat textFormat, float limitedToWidth = 0.0f, float limitedToHeight = 0.0f) 
{ 
    var device = CanvasDevice.GetSharedDevice(); 

    var layout = new CanvasTextLayout(device, text, textFormat, limitedToWidth, limitedToHeight); 

    var width = layout.DrawBounds.Width; 
    var height = layout.DrawBounds.Height; 

    return new Size(width, height); 
} 

您可以使用它像這樣:

string text = "Lorem ipsum dolor sit amet"; 

CanvasTextFormat textFormat = new CanvasTextFormat 
{ 
    FontSize = 16, 
    WordWrapping = CanvasWordWrapping.WholeWord, 
}; 

Size textSize = this.MeasureTextSize(text, textFormat, 320.0f); 

Source

相關問題