Brian Triplett
Brian Triplett

Reputation: 3532

Draw formatted text within a DrawingImage

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>

Upvotes: 5

Views: 4547

Answers (2)

alan xiang
alan xiang

Reputation: 111

<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>

Upvotes: 11

Ed Bayiates
Ed Bayiates

Reputation: 11210

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;
}

Upvotes: 2

Related Questions