# Monday, August 04, 2008

BabySmash Silverlight Refactorings - Part 1 - Adding Letters

After my initial port, alpha-numeric letters could not be rendered as the FormattedText object is not available within Silverlight. This left me with the following options:
  • Call a web service to dynamically convert the letters to the associated XAML path for a defines font.
  • Create a small WPF application that generates the XAML path geometry and embed this in a C# dictionary object within the code.

The second of the two options was the quickest (code snippet below). In the future another enhancement could look at creating web service or using a xap file with different fonts.

The next piece to the process was to load the path data into a Geometry instance. Using Alex Golesh's PathFigureCollectionConverter the shapes are now loaded and the updated version now supports generation of letters. One problem I have now if that the closed in shapes are not rendering properly i.e. the O is a solid oval.

var code = new StringBuilder();  
 
code.Append("var arial = new Dictionary<string, string>();\r\n");
var lettersToCreate = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 
for (var i = 0;i < lettersToCreate.Length; i++)
{
    var letter = lettersToCreate.Substring(i, 1);
    var fText = new FormattedText(
    letter,
    CultureInfo.CurrentCulture,
    FlowDirection.LeftToRight,
    new Typeface(
        new FontFamily("Arial"),
        FontStyles.Normal,
        FontWeights.Heavy,
        FontStretches.Normal),
    300,
    Brushes.Black
    );
    var g = fText.BuildGeometry(new Point(0, 0)).GetAsFrozen() as Geometry;
    // Get the Path info from the geometry
    var p = g.GetFlattenedPathGeometry();
 
    code.Append("arial.Add(\"" + letter + "\", \"" + p.ToString().Replace("F1M", "M ") + "\");\r\n");
}