【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>鍵調試運行,就會看到下面的結果:

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM