C# 谢尔宾斯基地毯
时间: 2023-12-05 12:40:51 浏览: 94
谢尔宾斯基地毯是一种分形图形,可以使用C#编程语言进行绘制。下面是一个绘制谢尔宾斯基地毯的C#代码示例:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SierpinskiCarpet
{
public partial class Form1 : Form
{
private Graphics graphics;
private int depth;
public Form1()
{
InitializeComponent();
graphics = CreateGraphics();
depth = 0;
}
private void DrawSierpinskiCarpet(int x, int y, int width, int height, int depth)
{
if (depth == 0)
{
graphics.FillRectangle(Brushes.Black, x, y, width, height);
}
else
{
int newWidth = width / 3;
int newHeight = height / 3;
int newX = x + newWidth;
int newY = y + newHeight;
DrawSierpinskiCarpet(x, y, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(newX, y, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(newX + newWidth, y, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(x, newY, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(newX + newWidth, newY, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(x, newY + newHeight, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(newX, newY + newHeight, newWidth, newHeight, depth - 1);
DrawSierpinskiCarpet(newX + newWidth, newY + newHeight, newWidth, newHeight, depth - 1);
}
}
private void button1_Click(object sender, EventArgs e)
{
graphics.Clear(Color.White);
depth++;
DrawSierpinskiCarpet(0, 0, Width, Height, depth);
}
private void button2_Click(object sender, EventArgs e)
{
graphics.Clear(Color.White);
depth--;
DrawSierpinskiCarpet(0, 0, Width, Height, depth);
}
}
}
```
这段代码使用了Windows Forms框架,创建了一个窗体,通过点击按钮可以增加或减少谢尔宾斯基地毯的深度。在DrawSierpinskiCarpet方法中,使用递归的方式绘制了谢尔宾斯基地毯的每一层。在绘制最底层时,使用黑色填充矩形来表示地毯的一部分。
阅读全文