【问题标题】:WPF C# Path: How to get from a string with Path Data to Geometry in Code (not in XAML)WPF C#路径:如何从带有路径数据的字符串到代码中的几何图形(不在 XAML 中)
【发布时间】:2011-01-03 00:49:36
【问题描述】:

我想在代码中生成一个 WPF Path 对象。

在 XAML 中我可以这样做:

 <Path Data="M 100,200 C 100,25 400,350 400,175 H 280">

如何在 Code 中做同样的事情?

 Path path = new Path();
 Path.Data = "foo"; //This won't accept a string as path data.

是否有可用的类/方法将带有 PathData 的字符串转换为 PathGeometry 或类似的?

肯定会以某种方式解析 XAML 并转换数据字符串?

【问题讨论】:

    标签: c# wpf path


    【解决方案1】:

    从原始文本字符串制作几何图形您可以使用 System.Windows.Media.FormattedText 类和 BuildGeometry() 方法

     public  string Text2Path()
        {
            FormattedText formattedText = new System.Windows.Media.FormattedText("Any text you like",
                CultureInfo.GetCultureInfo("en-us"),
                  FlowDirection.LeftToRight,
                   new Typeface(
                        new FontFamily(),
                        FontStyles.Italic,
                        FontWeights.Bold,
                        FontStretches.Normal),
                        16, Brushes.Black);
    
            Geometry geometry = formattedText.BuildGeometry(new Point(0, 0));
    
            System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
            path.Data = geometry;
    
            string geometryAsString = geometry.GetFlattenedPathGeometry().ToString().Replace(",",".").Replace(";",",");
            return geometryAsString;
        }
    

    【讨论】:

    • 不正确,我想知道你是如何获得 4 票的。
    【解决方案2】:

    你可以使用绑定机制。

    var b = new Binding
    {
       Source = "M 100,200 C 100,25 400,350 400,175 H 280"
    };
    BindingOperations.SetBinding(path, Path.DataProperty, b);
    

    希望对你有帮助。

    【讨论】:

    • 事实证明,您必须为 Windows 应用商店和手机应用程序执行此操作。 Geometry.Parse 位于该配置文件不支持的命名空间中。
    【解决方案3】:
    var path = new Path();
    path.Data = Geometry.Parse("M 100,200 C 100,25 400,350 400,175 H 280");
    

    Path.Data 是几何类型。使用 Reflector JustDecompile (eff Red Gate),我查看了 Geometry 的 TypeConverterAttribute 定义(xaml 序列化程序使用它来将 string 类型的值转换为 @987654324 @)。这将我指向 GeometryConverter。查看实现,我看到它使用Geometry.Parse 将路径的字符串值转换为几何实例。

    【讨论】:

    • 好吧,我花了一分钟在谷歌上搜索答案,但没有找到任何合理的答案。所以,在这种情况下(必须存在简单的解决方案),我偷看了代码。了解了 WPF 如何从字符串转换为复杂类型后,我就跟在了前面。了解过程对于知道答案至关重要。
    • @Peterdk:WP7 中有替代方案吗? WP7 Path 如何将字符串转换为几何?
    • @Nasenbaer:这很不幸。如果您按照我为确定桌面 WPF 应用程序的执行方式而执行的相同步骤,您可以找到商店应用程序的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多