WEB开发网
开发学院图形图像Flash Silverlight 画分形(Koch曲线) 阅读

Silverlight 画分形(Koch曲线)

 2008-12-08 11:51:42 来源:WEB开发网   
核心提示:Koch曲线是一类平面曲线:从一条线段中间三分之一的部分用等边三角形的两条边代替,形成的图形有四条边,Silverlight 画分形(Koch曲线),五个节点,再依次组成边的每条线段做相同的处理,用随机颜色,画完后为雪花状,迭代如图:稍微变换一下,画成六边形的

Koch曲线是一类平面曲线:从一条线段中间三分之一的部分用等边三角形的两条边代替,形成的图形有四条边,五个节点。再依次组成边的每条线段做相同的处理。

迭代如图:

Silverlight 画分形(Koch曲线)

稍微变换一下,画成六边形的,凸起方向向两边,用随机颜色,画完后为雪花状。

程序代码:

private void LayoutRoot_Loaded(object sender, RoutedEventArgs ea)
{
  double sqrt3 = Math.Sqrt(3);
  Point a = new Point(50, (float)(100 + 50 * sqrt3));
  Point b = new Point(100, (float)(100 + 100 * sqrt3));
  Point c = new Point(200, (float)(100 + 100 * sqrt3));
  Point d = new Point(250, (float)(100 + 50 * sqrt3));
  Point e = new Point(200, 100);
  Point f = new Point(100, 100);
  line(a, b, 5);
  line(b, a, 5);
  line(b, c, 5);
  line(c, b, 5);
  line(c, d, 5);
  line(d, c, 5);
  line(d, e, 5);
  line(e, d, 5);
  line(e, f, 5);
  line(f, e, 5);
  line(f, a, 5);
  line(a, f, 5);
}
private void line(Point a, Point b, int n)
{
  if (n > 0)
  {
    double r = Math.Atan(Math.Abs(a.Y - b.Y) / Math.Abs(a.X - b.X)); //角度
    double v = 0;
    Point c = new Point(a.X + (b.X - a.X) / 3, a.Y + (b.Y - a.Y) / 3);
    Point d = new Point(a.X + 2 * (b.X - a.X) / 3, a.Y + 2 * (b.Y - a.Y) / 3);
    double l = Math.Sqrt((c.X - d.X) * (c.X - d.X) + (c.Y - d.Y) * (c.Y - d.Y));
    Point e;
    if (b.Y - a.Y >= 0 && b.X - a.X > 0)
    {
      v = r;
    }
    else if (b.Y - a.Y > 0 && b.X - a.X <= 0)
    {
      v = Math.PI - r;
    }
    else if (b.Y - a.Y <= 0 && b.X - a.X < 0)
    {
      v = Math.PI + r;
    }
    else if (b.Y - a.Y < 0 && b.X - a.X >= 0)
    {
      v = 2 * Math.PI - r;
    }
    e = new Point((float)(l * Math.Cos(v + Math.PI / 3) + c.X), (float)(c.Y + l * Math.Sin(v + Math.PI / 3)));
    line(a, c, n - 1);
    line(c, e, n - 1);
    line(e, d, n - 1);
    line(d, b, n - 1);
  }
  else
  {
    Line l = new Line();
    Random rnd = new Random();
    Color c = Color.FromArgb(255, (byte)rnd.Next(255), (byte)rnd.Next(255), (byte)rnd.Next());
    l.Stroke = new SolidColorBrush(c);
    l.X1 = a.X;
    l.Y1 = a.Y;
    l.X2 = b.X;
    l.Y2 = b.Y;
    LayoutRoot.Children.Add(l);
  }
}
运行结果如图:

Silverlight 画分形(Koch曲线)

Koch曲线的每一部分都由4个跟它自身比例为1:3的形状相同的小曲线组成,那么它的豪斯多夫维数(分维数)为d=log(4)/log(3) =1.26185950714...

Tags:Silverlight Koch 曲线

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接