它返回一个Geometry,但这是一个抽象类。
我正在创建一个文本形状,并希望缓存此几何
BuildGeometry
可以返回不同的类型,感到怀疑,因此我可能做错了。我可以破解代码(一旦运行就会执行)但是我怎么能确定它总是会是同一类型的呢?
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));
}
}
答案 0 :(得分:3)
如果您在formattedtext.BuildGeometry
设置断点并检查返回的值,您会发现它是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...
}
}
当我使用简单的FormattedText测试时,顶级GeometryGroup的子节点本身就是GeometryGroups,PathGeometries作为它们的子节点。我的假设是,二级GeometryGroups每个都包含FormattedText对象的一个文本行,而PathGeometries包含单个字符或字形。
答案 1 :(得分:0)
从您的代码中看起来像RectangleGeometry
。
RectangleGeometry geometry = new RectangleGeometry();
protected override Geometry DefiningGeometry
{
get { return geometry; }
}