C#:7色分形樹-繪製
阿新 • • 發佈:2018-12-30
0.
遞迴思想,先畫樹幹,然後畫左樹,然後畫右樹,然後遞迴。
1.程式碼如下:
using System; using System.Drawing; using System.Windows.Forms; namespace DrawingTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.ClientSize = new Size(500,500); //設定窗體大小 } static private Graphics graphics; const double PI = Math.PI; static int cd = 40; //可調整左右彎曲程度不一樣或一樣 越大,越彎曲 static int cd2 = 40; static double th1 = cd * Math.PI / 180; //往右偏移程度 越大,越彎曲 static double th2 = cd2 * Math.PI / 180; //往左偏移程度 越大,越彎曲 static double per1 = 0.6; //往右的密集程度 0-1 0.6 可調整左右密集程度不一樣或一樣 static double per2 = 0.6; //往左的密集程度 0-1 0.6 static Graphics gp; //窗體的畫板 private void Form1_Paint_1(object sender, PaintEventArgs e) { gp = e.Graphics; drawTree(10, 250, 400, 100, -PI / 2); } //n決定整棵樹樹的密集程度 static void drawTree(int n, double x0, double y0, double leng, double th ) { if (n == 0) { return; } double x1 = x0 + leng * Math.Cos(th); //th=-90 th增加x往右偏 th減少x往左偏 double y1 = y0 + leng * Math.Sin(th); //th=-90 不管th增加減少,y都要減少 drawLine(x0, y0, x1, y1, n / 2); drawTree(n - 1, x1, y1, per1 * leng, th + th1); //繪製右邊的樹,th增加 x往右偏移 drawTree(n - 1, x1, y1, per2 * leng, th - th2); //繪製左邊的樹,th減少 x往左偏移 } private static void drawLine(double x0,double y0,double x1,double y1,int width) { Color color = Color.Black; Random rm = new Random(); int n = rm.Next(0,7);//0 1 2 3 4 5 6 switch (n) { case 0: color = Color.Black; break; case 1: color = Color.Blue; break; case 2: color = Color.Red; break; case 3: color = Color.Yellow; break; case 4: color = Color.Green; break; case 5: color = Color.Violet;//紫 break; case 6: color = Color.Firebrick; break; } Pen p = new Pen(color, width); gp.DrawLine(p,(int)x0,(int)y0,(int)x1,(int)y1); } } }
cd=40時:
cd=90時: