テキストに縁取りを付ける

2021-03-14

参照
WPF – 文字の縁取り方法 – astel-labs.net
WPF – 文字の縁取りをする – astel-labs.net

FontBorderTextBlock.xaml

<Grid x:Class="FontBorder.FontBorderTextBlock"
        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:FontBorder"
        mc:Ignorable="d">

    <TextBlock Text="{Binding Text}" Foreground="{Binding BorderColor}" FontSize="{Binding FontSize}">
        <TextBlock.RenderTransform>
            <TranslateTransform X="0" Y="1" />
        </TextBlock.RenderTransform>
    </TextBlock>
    <TextBlock Text="{Binding Text}" Foreground="{Binding BorderColor}" FontSize="{Binding FontSize}">
        <TextBlock.RenderTransform>
            <TranslateTransform X="0" Y="-1" />
        </TextBlock.RenderTransform>
    </TextBlock>
    <TextBlock Text="{Binding Text}" Foreground="{Binding BorderColor}" FontSize="{Binding FontSize}">
        <TextBlock.RenderTransform>
            <TranslateTransform X="1" Y="0" />
        </TextBlock.RenderTransform>
    </TextBlock>
    <TextBlock Text="{Binding Text}" Foreground="{Binding BorderColor}" FontSize="{Binding FontSize}">
        <TextBlock.RenderTransform>
            <TranslateTransform X="-1" Y="0" />
        </TextBlock.RenderTransform>
    </TextBlock>
    <TextBlock Text="{Binding Text}" Foreground="{Binding Foreground}" FontSize="{Binding FontSize}" />

</Grid>

FontBorderTextBlock.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace FontBorder
{
    /// <summary>
    /// FontBorderTextBlock.xaml の相互作用ロジック
    /// </summary>
    public partial class FontBorderTextBlock : Grid
    {
        public string Text { get; set; } = "";

        public string Foreground { get; set; } = "Black";

        public string BorderColor { get; set; } = "White";

        public double FontSize { get; set; } = SystemFonts.MessageFontSize;

        public FontBorderTextBlock()
        {
            InitializeComponent();

            this.DataContext = this;
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApp16.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:WpfApp16"
        xmlns:fontborder="clr-namespace:FontBorder;assembly=FontBorder"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="300">
    <Grid>
        <fontborder:FontBorderTextBlock Text="本日は晴天なり" Foreground="White" BorderColor="Black" FontSize="30"/>
    </Grid>
</Window>