C#寫的雪花分形


C#都沒人用了嗎,網上想找個現成的雪花分形代碼,都沒找見,有C++,有python,有java的,就沒有C#的,自己試試寫一個吧。

 1 public partial class Form1 : Form
 2     {
 3         public Form1()
 4         {
 5             InitializeComponent();
 6         }
 7 
 8         private void Form1_Paint(object sender, PaintEventArgs e)
 9         {
10             DrawKochSnow(e.Graphics);
11         }
12 
13         private void ZheXian(Point p1, Point p2, Graphics g)    // 4條基本線段組成的折線
14         {
15             Point p3 = new Point(p1.X + (p2.X - p1.X) / 3, p1.Y + (p2.Y - p1.Y) / 3);    // 三等分點坐標
16             Point p4 = new Point(p1.X + (p2.X - p1.X) * 2 / 3, p1.Y + (p2.Y - p1.Y) * 2 / 3);    // 三等分點坐標
17             Point p4XD3 = new Point(p4.X - p3.X, p4.Y - p3.Y);    // p4相對於p3點的坐標
18             //int x = (int)(p4XD3.X * Math.Cos(Math.PI / 3) - p4XD3.Y * Math.Sin(Math.PI / 3));
19             //int y = (int)(p4XD3.X * Math.Sin(Math.PI / 3) + p4XD3.Y * Math.Cos(Math.PI / 3));
20             // 注意計算機的屏幕垂直坐標和數學上相反,所以數學上逆時針旋轉在計算機上相當於順時針旋轉
21             int x = (int)Math.Round(p4XD3.X * Math.Cos(Math.PI / 3) + p4XD3.Y * Math.Sin(Math.PI / 3));
22             int y = (int)Math.Round(p4XD3.Y * Math.Cos(Math.PI / 3) - p4XD3.X * Math.Sin(Math.PI / 3));
23             Point p5XD3 = new Point(x, y);    // 凸起點p5相對於p3點的坐標
24             Point p5 = new Point(p3.X + x, p3.Y + y);    // p5相對於原點的坐標
25             Pen pen = new Pen(Brushes.Black, 1);
26             double length = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)) / 3;
27             //Console.WriteLine(length);
28             if (length > 20)    // 通過最終線段長度可以控制迭代
29             {
30                 ZheXian(p1, p3, g);
31                 ZheXian(p3, p5, g);
32                 ZheXian(p5, p4, g);
33                 ZheXian(p4, p2, g);
34             }
35             else
36             {
37                 g.DrawLine(pen, p1, p3);
38                 g.DrawLine(pen, p3, p5);
39                 g.DrawLine(pen, p5, p4);
40                 g.DrawLine(pen, p4, p2);
41             }
42         }
43 
44         private void DrawKochSnow(Graphics g)    // 科赫雪花(瑞典人科赫於1904年提出了著名的“雪花”曲線)
45         {
46             int length = 480;
47             Point origin = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
48             g.FillEllipse(Brushes.Blue, new RectangleF(origin, new Size(10, 10)));
49             // 計算三角形的頂點讓其中心和窗體的中心重合
50             Point A = new Point(origin.X - length / 2, (int)(origin.Y + length / (2 * Math.Sqrt(3))));
51             Point B = new Point(origin.X, (int)(origin.Y - length / Math.Sqrt(3)));
52             Point C = new Point(origin.X + length / 2, (int)(origin.Y + length / (2 * Math.Sqrt(3))));
53             ZheXian(A, B, g);
54             ZheXian(B, C, g);
55             ZheXian(C, A, g);
56         }
57     }

 雖然可能寫的不咋的,還是分享一下吧,大神請輕點噴。


免責聲明!

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



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