WPF 描述正弦、余弦关系几何动画

按照cos、sin运动轨迹描绘做出几何图像。参照此类方式可制作多种动态数学几何图形。
代码均为后台代码,可加强对path、曲线、扇形、storyboard等知识的学习理解。
最开始运行0.5秒,描述有些不整齐,自行修正。
编译最好设置“优化代码”。
代码可以优化,如有错误自行修正。
那个sin、cos文字写反了,sin在下面cos在上面,自己改下

图像录制效果不好,在代码中运行查看效果。
在这里插入图片描述
前台

<Window x:Class="Math_1.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:Math_1"
        mc:Ignorable="d"
        Title="MainWindow" Height="650" Width="1000" WindowStyle="None" WindowStartupLocation="CenterScreen">
    <Grid x:Name="mainGrid">
        <Canvas x:Name="mainBox"/>
    </Grid>
</Window>

后台

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Math_1
{
    public partial class MainWindow : Window
    {
        private Polyline pcurve_cos, pcurve_sin;

        private string rotation = "M 0,0 A 100,100 45 1 0 0,1 Z";
        private Storyboard story_circular, story_lineCircular, story_arc;
        private LineGeometry line_circular, line_sin, line_cos;

        private EllipseGeometry circular_elips, cosx_elips, cosy_elips, sin_elips;
        private Path path_CosSector;

        private double delay = 6;

        public MainWindow()
        {
            InitializeComponent();
            // 退出程序
            Button colse_btn = new Button()
            {
                Width = 60,
                Height = 22,
                Content = "退出"
            };
            colse_btn.Click += (s,e)=> { Close(); };
            Canvas.SetLeft(colse_btn,900);
            Canvas.SetTop(colse_btn,550);
            mainBox.Children.Add(colse_btn);
            // cos曲线点描述
            pcurve_cos = new Polyline()
            {
                Stroke = Brushes.Blue,
                StrokeThickness = 1
            };
            mainBox.Children.Add(pcurve_cos);
            // sin曲线点描述
            pcurve_sin = new Polyline()
            {
                Stroke = Brushes.Red,
                StrokeThickness = 1
            };
            mainBox.Children.Add(pcurve_sin);
            // 开始描述
            Draw_init(mainBox);
        }

        /// <summary>
        /// 描述cos、sin图像
        /// </summary>
        /// <param name="obj">父容器</param>
        private void Draw_init(Canvas obj)
        {
            // 绘制坐标
            Draw_Line(obj, new Point(100, 300), new Point(870, 300), Colors.LightSlateGray, 0.5);
            Draw_Line(obj, new Point(600, 20), new Point(600, 570), Colors.LightSlateGray, 0.5);

            // 绘制背景网格横线
            for (int i = 0; i < 6; i++)
            {
                double r = i < 3 ? 600 : 870;
                Draw_Line(obj, new Point(100, 50 + i * 100), new Point(r, 50 + i * 100), Colors.LightSlateGray, 0.1);
            }
            // 绘制背景网格竖线、弧线
            for (int i=0;i<3;i++)
            {
                Draw_Line(obj, new Point(450-i*150, 50), new Point(450-i*150, 250), Colors.LightSlateGray, 0.1);
                Draw_Line(obj, new Point(450 - i * 150, 350), new Point(450 - i * 150, 550), Colors.LightSlateGray, 0.1);
                Draw_Line(obj, new Point(650 + i * 100, 300), new Point(650 + i * 100, 570), Colors.LightSlateGray, 0.2);
                Path bsin = new Path()
                {
                    Stroke = Brushes.LightSlateGray,
                    StrokeThickness = 0.2,
                    Data = Geometry.Parse("M 0, -" + (50 + i * 100) + "  A" + (50 + i * 100) + ", " + (50 + i * 100) + " 0 0 1 " + (50 + i * 100) + ", 0")
                };
                Canvas.SetLeft(bsin, 600);
                Canvas.SetTop(bsin, 300);
                obj.Children.Add(bsin);
            }
            // 文字
            string[] ctext = new string[] { "Sin","Cos"};
            for (int i = 0; i < 2; i++)
            {
                Color color = i == 0 ? Colors.Blue : Colors.Red;
                TextBlock text = new TextBlock()
                {
                    Foreground = new SolidColorBrush(color),
                    FontSize = 15,
                    FontWeight = FontWeights.Bold,
                    FontStyle = FontStyles.Oblique,
                    Text = ctext[i],
                    Opacity = 0.6
                };
                Canvas.SetLeft(text, 100);
                Canvas.SetTop(text, 25+i*300);
                obj.Children.Add(text);

                TextBlock flag = new TextBlock()
                {
                    Foreground = Brushes.DarkOrange,
                    FontSize = 15,
                    FontWeight = FontWeights.Bold,
                    FontStyle = FontStyles.Oblique,
                    Text = "θ",
                    Opacity = 0.6
                };
                Canvas.SetLeft(flag, 130);
                Canvas.SetTop(flag, 25 + i * 300);
                obj.Children.Add(flag);
            }

            TextBlock angel_flag = new TextBlock()
            {
                Foreground = Brushes.DarkOrange,
                FontSize = 15,
                FontWeight = FontWeights.Bold,
                FontStyle = FontStyles.Oblique,
                Text = "θ = ",
                Opacity = 0.6
            };
            Canvas.SetLeft(angel_flag, 780);
            Canvas.SetTop(angel_flag, 40 );
            obj.Children.Add(angel_flag);

            // 圆外框
            Path path_border = new Path()
            {
                Stroke = Brushes.Green,
                StrokeThickness = 1,
                Data = Geometry.Parse(rotation)

            };
            Canvas.SetLeft(path_border, 850);
            Canvas.SetTop(path_border, 450);
            obj.Children.Add(path_border);

            // 圆内、外线段
            line_circular = new LineGeometry()
            {
                StartPoint = new Point(-100, 0),
                EndPoint = new Point(0, 0)
            };
            Path path_lineCircular = new Path()
            {
                Stroke = Brushes.LightGreen,
                StrokeThickness = 1,
                Data = line_circular
            };
            obj.RegisterName("LineCircular", line_circular);
            Canvas.SetLeft(path_lineCircular, 850);
            Canvas.SetTop(path_lineCircular, 450);
            obj.Children.Add(path_lineCircular);

            story_lineCircular = new Storyboard();
            PathGeometry pathLineCircularGeometry = new PathGeometry()
            {
                Figures = PathFigureCollection.Parse(rotation)
            };
            Set_Locus(obj, pathLineCircularGeometry, delay, "LineCircular", "EndPoint", story_lineCircular);
            story_lineCircular.Begin(obj, true);
            story_lineCircular.Pause(obj);

            // 圆心点、运动轨迹
            circular_elips = new EllipseGeometry()
            {
                Center = new Point(0, 0),
                RadiusX = 3,
                RadiusY = 3,
            };
            Path path_circular = new Path()
            {
                Fill = Brushes.Green,
                Data = circular_elips,
            };
            Panel.SetZIndex(path_circular,999);
            obj.RegisterName("Circular", circular_elips);
            Canvas.SetLeft(path_circular, 850);
            Canvas.SetTop(path_circular, 450);
            obj.Children.Add(path_circular);

            story_circular = new Storyboard();
            PathGeometry pathGeometry = new PathGeometry()
            {
                Figures = PathFigureCollection.Parse("M 0,0 A 100,100 45 1 0 0,1 Z")
            };
            Set_Locus(obj, pathGeometry, delay, "Circular", "Center", story_circular);
            story_circular.Begin(obj, true);
            story_circular.Pause(obj);

            // 圆内扇形
            Draw_Sector(obj);

            // 圆内圆心点
            EllipseGeometry center_elips = new EllipseGeometry()
            {
                Center = new Point(0, 0),
                RadiusX = 3,
                RadiusY = 3,
            };
            Path path_center = new Path()
            {
                Fill = Brushes.DarkOrange,
                Data = center_elips
            };
            Canvas.SetLeft(path_center, 750);
            Canvas.SetTop(path_center, 450);
            obj.Children.Add(path_center);

            // 圆外指示线段
            line_cos = new LineGeometry()
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 150)
            };
            Path path_lineCos = new Path()
            {
                Stroke = Brushes.LightBlue,
                StrokeThickness = 1,
                Data = line_cos
            };
            Canvas.SetLeft(path_lineCos, 850);
            Canvas.SetTop(path_lineCos, 300);
            obj.Children.Add(path_lineCos);

            line_sin = new LineGeometry()
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(150, 0)
            };
            Path path_lineSin = new Path()
            {
                Stroke = Brushes.LightCoral,
                StrokeThickness = 1,
                Data = line_sin
            };
            Canvas.SetLeft(path_lineSin, 600);
            Canvas.SetTop(path_lineSin, 450);
            obj.Children.Add(path_lineSin);

            // 圆内扇、扇形运动轨迹
            path_CosSector = new Path()
            {
                Stroke = Brushes.LightBlue,
                Data = Geometry.Parse("M0, 0 L0, -250 A250, 250 0 0 1 250, 0")
            };
            Canvas.SetLeft(path_CosSector, 600);
            Canvas.SetTop(path_CosSector, 300);
            obj.Children.Add(path_CosSector);

            cosx_elips = new EllipseGeometry()
            {
                Center = new Point(0, 0),
                RadiusX = 3,
                RadiusY = 3,
            };
            Path path_cosx = new Path()
            {
                Fill = Brushes.Blue,
                Data = cosx_elips
            };
            cosx_elips.Changed += Cosx_elips_Changed;
            Canvas.SetLeft(path_cosx, 850);
            Canvas.SetTop(path_cosx, 300);
            Panel.SetZIndex(path_cosx, 999);
            obj.Children.Add(path_cosx);

            cosy_elips = new EllipseGeometry()
            {
                Center = new Point(0, -50),
                RadiusX = 3,
                RadiusY = 3,
            };
            Path path_cosy = new Path()
            {
                Fill = Brushes.Blue,
                Data = cosy_elips
            };
            Canvas.SetLeft(path_cosy, 600);
            Canvas.SetTop(path_cosy, 100);
            Panel.SetZIndex(path_cosy, 999);
            obj.Children.Add(path_cosy);

            sin_elips = new EllipseGeometry()
            {
                Center = new Point(0, 0),
                RadiusX = 3,
                RadiusY = 3,
            };
            Path path_sin = new Path()
            {
                Fill = Brushes.Red,
                Data = sin_elips
            };
            sin_elips.Changed += Sin_elips_Changed;
            Canvas.SetLeft(path_sin, 600);
            Canvas.SetTop(path_sin, 450);
            Panel.SetZIndex(path_sin,999);
            obj.Children.Add(path_sin);

            // 开始动画
            story_circular.Begin(obj, true);
            story_lineCircular.Begin(obj, true);
            story_arc.Begin(obj, true);
            Task.Factory.StartNew(() => { Modify_Sector(); });
        }

        /// <summary>
        /// sin坐标值发生变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sin_elips_Changed(object sender, EventArgs e)
        {
            double radius = Math.Abs(250 + circular_elips.Center.X);
            path_CosSector.Data = Geometry.Parse("M0, 0 L0, " + (-radius) + " A" + radius + ", " + radius + " 0 0 1 " + radius + ", 0");

            for (int i = 0; i < pcurve_sin.Points.Count; i++)
            {
                pcurve_sin.Points[i] = new Point(pcurve_sin.Points[i].X - 1, pcurve_sin.Points[i].Y);
            }
            pcurve_sin.Points.Add(new Point(598, sin_elips.Center.Y + 450));
            if (pcurve_sin.Points.Count > 500)
            {
                pcurve_sin.Points.RemoveAt(0);
            }
        }

        /// <summary>
        /// cos坐标值发生变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cosx_elips_Changed(object sender, EventArgs e)
        {
            double radius = Math.Abs(250 + circular_elips.Center.X);
            path_CosSector.Data = Geometry.Parse("M0, 0 L0, " + (-radius) + " A" + radius + ", " + radius + " 0 0 1 " + radius + ", 0");

            for (int i = 0; i < pcurve_cos.Points.Count; i++)
            {
                pcurve_cos.Points[i] = new Point(pcurve_cos.Points[i].X - 1, pcurve_cos.Points[i].Y);
            }
            pcurve_cos.Points.Add(new Point(598, cosy_elips.Center.Y + 100));
            if (pcurve_cos.Points.Count > 500)
            {
                pcurve_cos.Points.RemoveAt(0);
            }
        }


        private Line line_axle, line_minaxle;
        private Path arc_move;
        private EllipseGeometry arc_elips;
        private Path pd, pn, min_pd, min_pn;

        /// <summary>
        /// 2个扇形、圆外线段位置变化 跨线程设置变动
        /// </summary>
        private void Modify_Sector()
        {
            while (true)
            {
                this.Dispatcher.InvokeAsync(() =>
                {
                    if (arc_elips.Center.Y <= 0)
                    {
                        pn.Data = Geometry.Parse("M0,0 L0,0 A0,0 0 0 1 0,0");
                        line_axle.Stroke = Brushes.Transparent;
                        string d = "M0,0 L" + (35 + arc_elips.Center.X) + "," + (arc_elips.Center.Y) + " A35,35 0 0 1 35,0 Z";
                        pd.Data = Geometry.Parse(d);

                        min_pn.Data = Geometry.Parse("M0,0 L0,0 A0,0 0 0 1 0,0");
                        line_minaxle.Stroke = Brushes.Transparent;
                        string md = "M0,0 L" + (35 + arc_elips.Center.X) + "," + (arc_elips.Center.Y) + " A35,35 0 0 1 35,0 Z";
                        min_pd.Data = Geometry.Parse(md);
                    }
                    else
                    {
                        pd.Data = Geometry.Parse("M -35, 0  A35, 35 0 0 1 35, 0");
                        line_axle.Stroke = Brushes.DarkOrange;
                        string n = "M0,0 L" + (35 + arc_elips.Center.X) + "," + (arc_elips.Center.Y) + " A35,35 0 0 1 -35,00";
                        pn.Data = Geometry.Parse(n);

                        min_pd.Data = Geometry.Parse("M -35, 0  A35, 35 0 0 1 35, 0");
                        line_minaxle.Stroke = Brushes.Gold;
                        string mn = "M0,0 L" + (35 + arc_elips.Center.X) + "," + (arc_elips.Center.Y) + " A35,35 0 0 1 -35,00";
                        min_pn.Data = Geometry.Parse(mn);
                    }

                    line_cos.StartPoint = new Point(circular_elips.Center.X, circular_elips.Center.Y + 150);
                    line_cos.EndPoint = new Point(circular_elips.Center.X, 0);
                    line_sin.StartPoint = new Point(0, circular_elips.Center.Y);
                    line_sin.EndPoint = new Point(circular_elips.Center.X + 250, circular_elips.Center.Y);

                    cosx_elips.Center = new Point(circular_elips.Center.X, 0);
                    cosy_elips.Center = new Point(0, -(circular_elips.Center.X + 50));
                    sin_elips.Center = new Point(0, circular_elips.Center.Y);
                });
                Thread.Sleep(5);
            }
        }

        /// <summary>
        /// 画2个扇形指示
        /// </summary>
        /// <param name="obj"></param>
        private void Draw_Sector(Canvas obj)
        {
            pd = new Path()
            {
                Fill = Brushes.Gold,
                Stroke = Brushes.DarkOrange,
                StrokeThickness = 0.5,
                Opacity = 0.5
            };
            Canvas.SetLeft(pd, 750);
            Canvas.SetTop(pd, 450);
            obj.Children.Add(pd);

            pn = new Path()
            {
                Fill = Brushes.Gold,
                Stroke = Brushes.DarkOrange,
                StrokeThickness = 0.5,
                Opacity = 0.5
            };
            Canvas.SetLeft(pn, 750);
            Canvas.SetTop(pn, 450);
            obj.Children.Add(pn);

            min_pd = new Path()
            {
                Fill = Brushes.LightGoldenrodYellow,
                Stroke = Brushes.Gold,
                StrokeThickness = 0.5,
            };
            Canvas.SetLeft(min_pd, 850);
            Canvas.SetTop(min_pd, 50);
            obj.Children.Add(min_pd);

            line_axle = new Line()
            {
                Stroke = Brushes.Transparent,
                StrokeThickness = 0.5,
                X1 = 750,
                Y1 = 450,
                X2 = 785,
                Y2 = 450,
                Opacity = 0.9
            };
            obj.Children.Add(line_axle);

            min_pn = new Path()
            {
                Fill = Brushes.LightGoldenrodYellow,
                Stroke = Brushes.Gold,
                StrokeThickness = 0.5,
            };
            Canvas.SetLeft(min_pn, 850);
            Canvas.SetTop(min_pn, 50);
            obj.Children.Add(min_pn);

            line_minaxle = new Line()
            {
                Stroke = Brushes.Transparent,
                StrokeThickness = 0.5,
                X1 = 850,
                Y1 = 50,
                X2 = 885,
                Y2 = 50,
            };
            obj.Children.Add(line_minaxle);

            Path min_elips = new Path()
            {
                Stroke = Brushes.Gold,
                StrokeThickness = 0.5,
                Data = Geometry.Parse("M 0, 0 A 35, 35 45 1 0 0, 1 Z")
            };
            Canvas.SetLeft(min_elips,885);
            Canvas.SetTop(min_elips,50);
            obj.Children.Add(min_elips);

           Path min_center = new Path()
            {
               Fill = Brushes.Gold,
               Data = Geometry.Parse("M 0, 0 A 3, 3 45 1 0 0, 1 Z")
           };
            Canvas.SetLeft(min_center, 852.5);
            Canvas.SetTop(min_center, 50);
            obj.Children.Add(min_center);

            arc_move = new Path();
            arc_elips = new EllipseGeometry() { Center = new Point(0, 0) };
            arc_move.Data = arc_elips;
            Canvas.SetLeft(arc_move, 783);
            Canvas.SetTop(arc_move, 450);
            obj.RegisterName("Arc_Move", arc_elips);
            obj.Children.Add(arc_move);

            story_arc = new Storyboard();
            PathGeometry fanGeometry = new PathGeometry()
            {
                Figures = PathFigureCollection.Parse("M 0,0 A 35,35 45 1 0 0,1 Z")
            };
            Set_Locus(obj, fanGeometry, delay, "Arc_Move", "Center", story_arc);
        }

        /// <summary>
        /// 设置运动轨迹
        /// </summary>
        /// <param name="obj">父容器</param>
        /// <param name="geo">路径</param>
        /// <param name="delay">延时</param>
        /// <param name="targetname">动画属性名称</param>
        /// <param name="value">属性名称</param>
        /// <param name="storyboard">动画板</param>
        private void Set_Locus(Canvas obj, PathGeometry geo, double delay, string targetname, string value, Storyboard storyboard)
        {
            PointAnimationUsingPath pointAnimationUsingPath = new PointAnimationUsingPath()
            {
                Duration = new Duration(TimeSpan.FromSeconds(delay)),
                RepeatBehavior = RepeatBehavior.Forever,
            };
            PathGeometry pathGeometry = geo;
            pointAnimationUsingPath.PathGeometry = pathGeometry;

            Storyboard.SetTargetName(pointAnimationUsingPath, targetname);
            Storyboard.SetTargetProperty(pointAnimationUsingPath, new PropertyPath(value));

            storyboard.Children.Add(pointAnimationUsingPath);
        }

        /// <summary>
        /// 画线
        /// </summary>
        /// <param name="obj">父容器</param>
        /// <param name="begin">开始位置</param>
        /// <param name="end">结束位置</param>
        /// <param name="stroke">颜色</param>
        /// <param name="thickness">粗细</param>
        private void Draw_Line(Canvas obj, Point begin, Point end, Color stroke, double thickness)
        {
            LineGeometry line = new LineGeometry()
            {
                StartPoint = begin,
                EndPoint = end
            };
            Path line_path = new Path() { Stroke = new SolidColorBrush(stroke), StrokeThickness = thickness, Data = line };
            obj.Children.Add(line_path);
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值