WPF 绘制曲线 例子
时间: 2023-05-11 10:06:43 浏览: 89
以下是一个简单的 WPF 绘制曲线的例子:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Canvas x:Name="canvas" Background="White" Width="600" Height="400" Margin="100,50,0,0"/>
</Grid>
</Window>
```
```csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DrawCurve();
}
private void DrawCurve()
{
Polyline polyline = new Polyline();
polyline.Stroke = Brushes.Black;
polyline.StrokeThickness = 2;
for (double x = -5; x <= 5; x += 0.1)
{
double y = Math.Sin(x);
Point point = new Point(x * 50 + 300, -y * 50 + 200);
polyline.Points.Add(point);
}
canvas.Children.Add(polyline);
}
}
```
这个例子使用 Canvas 和 Polyline 控件来绘制一条正弦曲线。在 DrawCurve 方法中,我们使用 for 循环计算出曲线上的每个点的坐标,并将这些点添加到 Polyline 的 Points 集合中。最后,我们将 Polyline 添加到 Canvas 中以显示出来。