昨日、「フラクタル図形の世界へのいざない」(http://qiita.com/kiuyas/items/dee169b7fea69519a18d )というお題でJava版の「コッホ曲線」と「シェルピンスキーのギャスケット」を描くコードを載せましたが、続きましてそのC#版をお届けします。
KochCurveという名前でWindowsフォームアプリケーションを作成し、Form1.csを以下のものに書き換えてください。
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace KochCurve
{
public partial class Form1 : Form
{
private const double PAI = 3.141592653589393238462643383279;
private const double thetaOf60Degree = 60 * PAI / 180;
private int maxLevel = 4;
public Form1()
{
InitializeComponent();
SetBounds(0, 0, 640, 480, BoundsSpecified.Size);
BackColor = Color.Black;
this.Text = "コッホ曲線";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawKochCurve(e.Graphics, 0, 100, 639, 100, 0);
}
private void DrawKochCurve(Graphics g, int x1, int y1, int x2, int y2, int level)
{
if (level == maxLevel)
{
g.DrawLine(Pens.Yellow, x1, 479 - y1, x2, 479 - y2);
}
else
{
int vx = (x2 - x1) / 3;
int vy = (y2 - y1) / 3;
int xx1 = x1 + vx;
int yy1 = y1 + vy;
int[] v1 = rotate(thetaOf60Degree, vx, vy);
int xx2 = xx1 + v1[0];
int yy2 = yy1 + v1[1];
int[] v2 = rotate(-thetaOf60Degree, vx, vy);
int xx3 = xx2 + v2[0];
int yy3 = yy2 + v2[1];
level++;
DrawKochCurve(g, x1, y1, xx1, yy1, level);
DrawKochCurve(g, xx1, yy1, xx2, yy2, level);
DrawKochCurve(g, xx2, yy2, xx3, yy3, level);
DrawKochCurve(g, xx3, yy3, x2, y2, level);
}
}
private int[] rotate(double theta, int x, int y)
{
double sinTheta = Math.Sin(theta);
double cosTheta = Math.Cos(theta);
int x2 = (int)(cosTheta * x - sinTheta * y);
int y2 = (int)(sinTheta * x + cosTheta * y);
return new int[] { x2, y2 };
}
}
}
##シェルピンスキーのギャスケット
SierpinskiGasketという名前でWindowsフォームアプリケーションを作成し、Form1.csを以下のものに書き換えてください。
Form1.cs
using System.Drawing;
using System.Windows.Forms;
namespace SierpinskiGasket
{
public partial class Form1 : Form
{
private int maxLevel = 6;
public Form1()
{
InitializeComponent();
SetBounds(0, 0, 640, 480, BoundsSpecified.Size);
BackColor = Color.Black;
this.Text = "シェルピンスキーのギャスケット";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawSierpinskiGasket(e.Graphics, 319, 40, 30, 430, 609, 430, 0);
}
private void DrawSierpinskiGasket(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int level)
{
if (level == maxLevel)
{
g.DrawLine(Pens.Lime, x1, y1, x2, y2);
g.DrawLine(Pens.Lime, x2, y2, x3, y3);
g.DrawLine(Pens.Lime, x3, y3, x1, y1);
}
else
{
int xx1 = (int)((x1 + x2) / 2.0);
int yy1 = (int)((y1 + y2) / 2.0);
int xx2 = (int)((x2 + x3) / 2.0);
int yy2 = (int)((y2 + y3) / 2.0);
int xx3 = (int)((x3 + x1) / 2.0);
int yy3 = (int)((y3 + y1) / 2.0);
DrawSierpinskiGasket(g, x1, y1, xx1, yy1, xx3, yy3, level + 1);
DrawSierpinskiGasket(g, x2, y2, xx1, yy1, xx2, yy2, level + 1);
DrawSierpinskiGasket(g, x3, y3, xx3, yy3, xx2, yy2, level + 1);
}
}
}
}
VB.NET版も近々アップします!
では。