[C# WPF] テキストのサイズを算出する
まずは手順から。WPFで文字列のサイズを取得する方法です。
XAML側
<Window x:Class="Sample_StringSize.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Sample_StringSize"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock x:Name="xTarget1"/>
<TextBlock x:Name="xResult1"/>
<TextBlock x:Name="xTarget2"/>
<TextBlock x:Name="xResult2"/>
</StackPanel>
</Window>
C#側
using System.Windows;
using System.Windows.Media;
namespace Sample_StringSize
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
{
xTarget1.Text = "Sample";
xTarget1.FontSize = 10;
var formattedText = new FormattedText(
xTarget1.Text,
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(xTarget1.FontFamily, xTarget1.FontStyle, xTarget1.FontWeight, xTarget1.FontStretch),
xTarget1.FontSize,
Brushes.Green
);
xResult1.Text = "Width: " + formattedText.Width + " / Height: " + formattedText.Height;
}
{
xTarget2.Text = "Sample";
xTarget2.FontSize = 100;
var formattedText = new FormattedText(
xTarget2.Text,
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(xTarget2.FontFamily, xTarget2.FontStyle, xTarget2.FontWeight, xTarget2.FontStretch),
xTarget2.FontSize,
Brushes.Green
);
xResult2.Text = "Width: " + formattedText.Width + " / Height: " + formattedText.Height;
}
}
}
}
単純なTextBlockのサイズは、こんな感じに値が取得できます。

表示しないでサイズを算出したい場合は、FormattedTextに設定する値を直接指定すればいいです。
var formattedText = new FormattedText(
"プリンたべたい",
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(
new FontFamily("Comic Sans MS"),
FontStyles.Italic,
FontWeights.Heavy,
FontStretches.Expanded
),
10,
Brushes.Green
);
xResult3.Text = "Width: " + formattedText.Width + " / Height: " + formattedText.Height;
表示してなくても、こんな感じに取得できます。

おしまい。





ディスカッション
コメント一覧
まだ、コメントがありません