Search code examples
c#wpfxamltextgeometrydrawing

How to use the GeometryDrawing?


I want to draw the letters A~Z by GeometryDrawing.


Solution

  • Here is an example how to draw text using GeometryDrawing.

    XAML file Window1.xaml:

    <Window x:Class="TextDrawing.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="150" Width="300">
        <Canvas>
            <Image Stretch="None" HorizontalAlignment="Left" Margin="10">
                <Image.Source>
                    <DrawingImage>
                        <DrawingImage.Drawing>
                            <GeometryDrawing x:Name="geoDrawing"/>
                        </DrawingImage.Drawing>
                    </DrawingImage>
                </Image.Source>
            </Image>
        </Canvas>
    </Window>
    

    C# file Window1.xaml.cs:

    using System.Windows;
    using System.Windows.Media;
    using System.Globalization;
    
    namespace TextDrawing
    {
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
    
                FormattedText atoz = new FormattedText("ABC...XYZ",
                    CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                    new Typeface("Arial"), 50.0, Brushes.Black);
                Geometry geo = atoz.BuildGeometry(new Point(0, 0));
                geoDrawing.Geometry = geo;
                geoDrawing.Pen = new Pen(Brushes.Black, 1.0);
                geoDrawing.Brush = Brushes.Yellow;
            }
        }
    }
    

    Resulting output:

    Text rendered with GeometryDrawing