It returns a Geometry, but that is an abstract class.
I am creating a text shape and want to cache this geometry.
That BuildGeometry
could returns different types, feels suspect and therefore I may be doing something wrong. I could break the code (will do as soon as it runs) but how can I be sure it will be of the same type always?
public class Label : ShapeBase
{
RectangleGeometry geometry = new RectangleGeometry();
protected override Geometry DefiningGeometry
{
get { return geometry; }
}
protected override Size MeasureOverride(Size constraint)
{
return constraint;
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(Label), new UIPropertyMetadata(string.Empty, OnTextChanged));
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Label label = (Label)d;
label.SetGeometry(label.Text);
label.InvalidateVisual();
}
private void SetGeometry(string text)
{
FormattedText formattedtext = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Tahoma"), 16, Brushes.Black);
GeometryGroup group = (GeometryGroup)formattedtext.BuildGeometry(new Point(0, 0));
}
}
If you set a breakpoint at formattedtext.BuildGeometry
and inspect the returned value, you'll realize that it is a GeometryGroup
:
var geometry = formattedText.BuildGeometry(new Point());
var geometryGroup = geometry as GeometryGroup;
if (geometryGroup != null)
{
foreach (var childGeometry in geometryGroup.Children)
{
// do something with the child geometries...
}
}
When I test this with a simple FormattedText, the children of the top-level GeometryGroup are themselves GeometryGroups, with PathGeometries as their children. My assumption is that the second-level GeometryGroups each contain one text row of the FormattedText object, whereas the PathGeometries contain single characters or glyphs.