5

I'm trying to include some formatted text as part of a drawing in XAML. Is this possible? How is it done?

Example:

<DrawingImage>
    <DrawingImage.Drawing>
      <!-- Can text be drawn here? -->
    </DrawingImage.Drawing>
</DrawingImage>
Brian Triplett
  • 3,462
  • 6
  • 35
  • 61

2 Answers2

9
<DrawingImage>
    <DrawingImage.Drawing>
        <GeometryDrawing>
            <GeometryDrawing.Geometry>
                <RectangleGeometry Rect="0,0,10,10"></RectangleGeometry>
            </GeometryDrawing.Geometry>
            <GeometryDrawing.Brush>
                <VisualBrush>
                    <VisualBrush.Visual>
                        <StackPanel>
                            <TextBlock  Text="Tyco" FontSize="16" FontWeight="999" Foreground="Black"></TextBlock>
                        </StackPanel>
                    </VisualBrush.Visual>
                </VisualBrush>
            </GeometryDrawing.Brush>
        </GeometryDrawing>
    </DrawingImage.Drawing>
</DrawingImage>
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
alan xiang
  • 91
  • 1
  • 2
2

Yes. Use a GlyphRunDrawing as part of the DrawingGroup or as the Drawing itself, that is the source of your DrawingImage. To construct the GlyphRun in Xaml is possible, and also in code behind:

Typeface typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal);
if (!typeface.TryGetGlyphTypeface(out _glyphTypeface))
    return;

_glyphIndexes = new ushort[text.Length];
_advanceWidths = new double[text.Length];

double textWidth = 0;
for (int ix = 0; ix < text.Length; ix++)
{
    ushort glyphIndex = _glyphTypeface.CharacterToGlyphMap[text[ix]];
    _glyphIndexes[ix] = glyphIndex;

    double width = _glyphTypeface.AdvanceWidths[glyphIndex] * FontSize;
   _advanceWidths[ix] = width;

   textWidth += width;
   double textHeight = _glyphTypeface.Height * FontSize;
}
Ed Bayiates
  • 11,060
  • 4
  • 43
  • 62
  • Very helpful. I've seen the examples in XAML but I can't see how to connect the AdvanceWidths and Height. Any ideas? – Brian Triplett Jul 15 '11 at 20:05
  • What do you mean by connect them? – Ed Bayiates Jul 15 '11 at 20:05
  • In your code-behind above the AdvanceWidths and glyphIndicies are set in a for loop. I would have no idea how to represent that in XAML. – Brian Triplett Jul 15 '11 at 20:32
  • 1
    In Xaml they are just as a list of numbers in quotes: GlyphIndices="43 72 79" AdvanceWidths="9.62 7.41 2.96" – Ed Bayiates Jul 15 '11 at 20:34
  • I saw that in the MSDN documentation. Any idea how to figure out the "correct" values? I've figured out the Inidicies for my text but have no idea how to get the AdvanceWidths for the various characters in my font (Segoe UI). – Brian Triplett Jul 15 '11 at 20:48
  • 1
    That's why I included the codebehind for you. You could insert a System.Diagnostics.Debug.WriteLine for each value calculated and grab the results from the debugger output window. – Ed Bayiates Jul 15 '11 at 20:54