【C#】第3章补充(一)如何在WPF中绘制正弦曲线
分类:C#、VS2015
创建日期:2016-06-19
使用教材:(十二五国家级规划教材)《C#程序设计及应用教程》(第3版)
一、要点
本例子提前使用了教材第13章介绍的基本知识。
二、设计步骤
1、新建一个名为MyTest1的WPF应用程序项目。
2、将MainWindow.xaml改为下面的内容。
<Window x:Class="MyTest1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:MyTest1" mc:Ignorable="d" Title="DrawSinWindow" Height="300" Width="700" Background="#FFDCECE5"> <Window.Resources> <Style TargetType="Path"> <Setter Property="StrokeThickness" Value="2" /> <Setter Property="RenderTransform"> <Setter.Value> <TransformGroup> <TranslateTransform X="360" Y="-110" /> <ScaleTransform ScaleY="-1" ScaleX="0.7" /> </TransformGroup> </Setter.Value> </Setter> </Style> </Window.Resources> <Canvas Name="canvas1" Width="500" Height="220" Margin="20"> <!--绘制坐标轴--> <Path Name="path1" Stroke="Red" Data="M-385,0 L385,0 375 5 M385,0 L375,-5 M0,-100 L0,105 -5,95 M0,105 L5,95"> </Path> <!--绘制正弦曲线--> <Path Name="path2" Stroke="Black"/> <Path Name="path3" Stroke="Blue"/> </Canvas> </Window>
3、将MainWindow.xaml.cs改为下面的内容。
using System; using System.Windows; using System.Windows.Media; namespace MyTest1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); GeometryGroup group1 = new GeometryGroup(); var g1 = GetSinGeometry(1, 100); group1.Children.Add(g1); path2.Data = group1; GeometryGroup group2 = new GeometryGroup(); var g2 = GetSinGeometry(60, 50); group2.Children.Add(g2); path3.Data = group2; } public StreamGeometry GetSinGeometry(int dx, int dy) { StreamGeometry g = new StreamGeometry(); using (StreamGeometryContext ctx = g.Open()) { int x0 = 360; double y0 = Math.Sin(-x0 * Math.PI / 180.0); ctx.BeginFigure(new Point(-x0, dy * y0), false, false); for (int x = -x0; x < x0; x += dx) { double y = Math.Sin(x * Math.PI / 180.0); ctx.LineTo(new Point(x, dy * y), true, true); } } g.Freeze(); return g; } } }
4、按<F5>键调试运行,就会看到下面的结果:

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架