如何使用 C# 构建 PathGeometry?

How to build PathGeometry using C#?

我在 Windows Phone 8.1 应用中有以下 XAML 运行 Windows Runtime:

<Canvas Name="drawSplice"
        Grid.Row="1"
        Grid.Column="0"
        Height="80"
        Width="80"
        Background="White">

        <Path Stroke="Black"
                      StrokeThickness="2"
                      Data="M 10,10 C 10,50 65,10 65,70" />
</Canvas>

它给了我以下形状:

我的问题是如何使用 C# 生成 path class 的实例?

Windows.UI.Xaml.Shapes.Path path = new Windows.UI.Xaml.Shapes.Path();

//path.Data = "";

path.StrokeThickness = 3;
path.Stroke = new SolidColorBrush(Colors.Black);
Drawer.Children.Add(path); 

您可以使用 XamlReader 从字符串中解析和加载 Xaml 对象。您需要一个完整的 Xaml 对象来读取路径数据,而不仅仅是数据本身:

// The path data we want to create
string pathXaml = "M 10,10 C 10,50 65,10 65,70";

// A Xaml container for the path object.
// This could also set other properties like Stroke and StrokeThickness
string xaml = "<Path " +
"xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
"<Path.Data>" + pathXaml + "</Path.Data></Path>";

// Read the Xaml string into a Path object
Windows.UI.Xaml.Shapes.Path path = XamlReader.Load(xaml) as Windows.UI.Xaml.Shapes.Path;

// Set other properties we skipped above
path.StrokeThickness = 3;
path.Stroke = new SolidColorBrush(Colors.Blue);

// Add it to our Canvas
drawSplice.Children.Add(path);

您也可以从对象构建路径。 Path.Data 是一个 PathGeometry,它包含一个 PathFigure(在你的例子中是一个,但可能更多),它包含 PathSegments(在你的例子中是一个 BezierSegment)。使用标记更容易。要查看其工作原理,您可以从标记或 XamlLoader 创建路径,然后检查其集合以查看其构建方式。

请注意,您 Xaml 中的路径与您包含的图像不匹配。给定的 Xaml 路径是立方贝塞尔曲线而不是椭圆。如果您想要椭圆,可以使用椭圆,或从 EllipseGeometry 或 ArcSegment 构建路径。

你可以用这个。对你有帮助。

string data = "M 10,10 C 10,50 65,10 65,70";
        string xaml = "<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Data='" + data + "'/>";
        var LoadPath = Windows.UI.Xaml.Markup.XamlReader.Load(xaml); 
        Windows.UI.Xaml.Shapes.Path path = LoadPath as Windows.UI.Xaml.Shapes.Path;
        path.StrokeThickness = 3;
        path.Stroke = new SolidColorBrush(Windows.UI.Colors.Black);
        drawSplice.Children.Add(path);

我使用了以下技巧:

var b = new Binding
{
   Source = "M 10,10 C 10,50 65,10 65,70"
};
BindingOperations.SetBinding(path, Path.DataProperty, b);

它在 Windows Phone 8.1 上运行良好。