Tag Archives: wpf

How to Use SVG Glyphs in XAML

Using SVG glyphs on web pages for custom icons is brilliant (see Font Awesome, GlyphIcons, …). The SVG glyphs are encoded using path expression to describe the vector graphics.

But wait! You can use the path expression to define a graphic element in XAML (which means WPF, Silverlight, WindowsPhone) too!

If you want to use the SVG glyphs in XAML here is a simple manual:

  1. download the font
  2. find the icon you want use (for example FontAwesome Suitcase icon  ) and its content value ("\f0f2")
  3. find the corresponding glyph in svg file

    <glyph unicode="&#xf0f2;" horiz-adv-x="1792" d="M640 1152h512v128h-512v-128zM288 1152v-1280h-64q-92 0 -158 66t-66 158v832q0 92 66 158t158 66h64zM1408 1152v-1280h-1024v1280h128v160q0 40 28 68t68 28h576q40 0 68 -28t28 -68v-160h128zM1792 928v-832q0 -92 -66 -158t-158 -66h-64v1280h64q92 0 158 -66 t66 -158z" />

  4. add new GeometryGroup with child PathGeometry to Resources in the XAML, set the value of PathGeometry.Figures property to d value of the glyph

    <GeometryGroup x:Key="Suitcase">
    <PathGeometry Figures="M640 1152h512v128h-512v-128zM288 1152v-1280h-64q-92 0 -158 66t-66 158v832q0 92 66 158t158 66h64zM1408 1152v-1280h-1024v1280h128v160q0 40 28 68t68 28h576q40 0 68 -28t28 -68v-160h128zM1792 928v-832q0 -92 -66 -158t-158 -66h-64v1280h64q92 0 158 -66 t66 -158z" />
    </GeometryGroup>

  5. Create DrawingImage. The geometry drawing must be turned upside down (see line 13). I googled around, but didn’t find out why.

     <DrawingImage x:Key="SuitcaseImage"> 
    <DrawingImage.Drawing> 
    <DrawingGroup> 
    <DrawingGroup.Children> 
    <GeometryDrawing Geometry="{StaticResource SuitcasePath}"> 
    <GeometryDrawing.Pen> 
    <Pen Thickness="5" Brush="Black" /> 
    </GeometryDrawing.Pen> 
    </GeometryDrawing> 
    </DrawingGroup.Children> 
    <DrawingGroup.Transform> 
    <TransformGroup> 
    <ScaleTransform ScaleY="-1" /> 
    </TransformGroup> 
    </DrawingGroup.Transform> 
    </DrawingGroup> 
    </DrawingImage.Drawing> 
    </DrawingImage> 

  6. use the DrawingImage as a source for an Image

    <Image Source="{StaticResource SuitcaseImage}" Width="150" Height="150" />

This is very simple approach how to use the glyphs in XAML. It does not allow you to easily reuse the icon with different colors (but you can change the line brush color on line 7 or set the Path.Fill brush) or it does not allow easy composition of icons (but you can add more GeometryDrawing to DrawingGroup.Children collection on line 5).

The complete code is available here, the result in Kaxaml editor: suitcase_screen