0

它返回一个几何,但那是一个抽象类。我正在创建一个文本形状并想要缓存这个几何图形。
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));
        }
    }
4

2 回答 2

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,而 PathGeometry 是它们的子级。我的假设是第二级 GeometryGroups 每个都包含 FormattedText 对象的一个​​文本行,而 PathGeometries 包含单个字符或字形。

于 2014-02-24T11:58:17.010 回答
0

从您的代码来看,它看起来像一个RectangleGeometry.

    RectangleGeometry geometry = new RectangleGeometry();

    protected override Geometry DefiningGeometry
    {
        get { return geometry; }
    }
于 2014-02-24T11:23:41.540 回答