c# 实现雪花分形的示例
#代码知识 发布时间: 2026-01-12
C#都没人用了吗,网上想找个现成的雪花分形代码,都没找见,有C++,有python,有java的,就没有C#的,自己试试写一个吧。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawKochSnow(e.Graphics);
}
private void ZheXian(Point p1, Point p2, Graphics g) // 4条基本线段组成的折线
{
Point p3 = new Point(p1.X + (p2.X - p1.X) / 3, p1.Y + (p2.Y - p1.Y) / 3); // 三等分点坐标
Point p4 = new Point(p1.X + (p2.X - p1.X) * 2 / 3, p1.Y + (p2.Y - p1.Y) * 2 / 3); // 三等分点坐标
Point p4XD3 = new Point(p4.X - p3.X, p4.Y - p3.Y); // p4相对于p3点的坐标
//int x = (int)(p4XD3.X * Math.Cos(Math.PI / 3) - p4XD3.Y * Math.Sin(Math.PI / 3));
//int y = (int)(p4XD3.X * Math.Sin(Math.PI / 3) + p4XD3.Y * Math.Cos(Math.PI / 3));
// 注意计算机的屏幕垂直坐标和数学上相反,所以数学上逆时针旋转在计算机上相当于顺时针旋转
int x = (int)Math.Round(p4XD3.X * Math.Cos(Math.PI / 3) + p4XD3.Y * Math.Sin(Math.PI / 3));
int y = (int)Math.Round(p4XD3.Y * Math.Cos(Math.PI / 3) - p4XD3.X * Math.Sin(Math.PI / 3));
Point p5XD3 = new Point(x, y); // 凸起点p5相对于p3点的坐标
Point p5 = new Point(p3.X + x, p3.Y + y); // p5相对于原点的坐标
Pen pen = new Pen(Brushes.Black, 1);
double length = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)) / 3;
//Console.WriteLine(length);
if (length > 20) // 通过最终线段长度可以控制迭代
{
ZheXian(p1, p3, g);
ZheXian(p3, p5, g);
ZheXian(p5, p4, g);
ZheXian(p4, p2, g);
}
else
{
g.DrawLine(pen, p1, p3);
g.DrawLine(pen, p3, p5);
g.DrawLine(pen, p5, p4);
g.DrawLine(pen, p4, p2);
}
}
private void DrawKochSnow(Graphics g) // 科赫雪花(瑞典人科赫于1904年提出了著名的“雪花”曲线)
{
int length = 480;
Point origin = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
g.FillEllipse(Brushes.Blue, new RectangleF(origin, new Size(10, 10)));
// 计算三角形的顶点让其中心和窗体的中心重合
Point A = new Point(origin.X - length / 2, (int)(origin.Y + length / (2 * Math.Sqrt(3))));
Point B = new Point(origin.X, (int)(origin.Y - length / Math.Sqrt(3)));
Point C = new Point(origin.X + length / 2, (int)(origin.Y + length / (2 * Math.Sqrt(3))));
ZheXian(A, B, g);
ZheXian(B, C, g);
ZheXian(C, A, g);
}
}
以上就是c# 实现雪花分形的示例的详细内容,更多关于c# 雪花分形的资料请关注其它相关文章!
代码知识SEO上一篇 : 在sql中对两列数据进行运算作为新的列操作
下一篇 : UDP简单服务端客户端代码示例
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!