C#:7色分形树-绘制

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时:

C#:7色分形树-绘制

cd=90时:

C#:7色分形树-绘制