Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw formatted text within a DrawingImage

Tags:

wpf

drawing

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>
like image 923
Brian Triplett Avatar asked Jul 15 '11 19:07

Brian Triplett


2 Answers

<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>
like image 57
alan xiang Avatar answered Sep 22 '22 23:09

alan xiang


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;
}
like image 27
Ed Bayiates Avatar answered Sep 22 '22 23:09

Ed Bayiates