WEB开发网
开发学院软件开发C语言 曼德勃罗特集图形的C#版本 阅读

曼德勃罗特集图形的C#版本

 2010-09-30 21:06:59 来源:WEB开发网   
核心提示:由于脑袋已经凌驾于语言之上,写出来的东东不利于C#er消化吸收,曼德勃罗特集图形的C#版本,经过0.n小时的努力,完成了这个图形的C#版本,因为这个玩意儿是典型的并行计算的场景,所以以下代码使用了.NET Framework 4.0里面的并行库(哦还有复数类)

由于脑袋已经凌驾于语言之上,写出来的东东不利于C#er消化吸收,经过0.n小时的努力,完成了这个图形的C#版本。

因为这个玩意儿是典型的并行计算的场景,所以以下代码使用了.NET Framework 4.0里面的并行库(哦还有复数类),已在VS2010下编译运行通过。大家可以自己调节参数玩。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Numerics;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;

namespace NinputerExam1
{
  class Program
  {
    static void Main( string[] args )
    {
      Size size = new Size( 4096, 4096 );
      int[] map = new int[size.Width * size.Height];
      var points = from x in Enumerable.Range( 0, size.Width ) from y in Enumerable.Range( 0, size.Height ) select new Point( x, y );

      Stopwatch watch = new Stopwatch();
      watch.Start();
      Console.WriteLine( "begin Calculate..." );
      points.AsParallel().ForAll( point => map[point.X * size.Height + point.Y] = Calculate( point, size ) );
      Console.WriteLine( "Calculate finished... Elapsed: {0}", watch.Elapsed );
      watch.Restart();

      var colorMap = Array.ConvertAll( map, value => ComposeColor( value ) );

      Console.WriteLine( "begin Drawing" );
      using ( var bitmap = new Bitmap( size.Width, size.Height, PixelFormat.Format32bppRgb ) )
      {

        for ( int x = 0; x < size.Width; x++ )
        {
          for ( int y = 0; y < size.Height; y++ )
          {
            bitmap.SetPixel( x, y, colorMap[x * size.Height + y] );
          }
        }
        using ( var stream = new FileStream( @"c:\Temp\1.png", FileMode.Create, FileAccess.Write ) )
        {
          bitmap.Save( stream, ImageFormat.Png );
        }
      }
      Console.WriteLine( "Drawing finished... Elapsed: {0}", watch.Elapsed );
      Console.ReadLine();
    }
    private const int maxIter = 4096;
    public static int Calculate( Point point, Size size )
    {
      Complex c = new Complex( (double) point.X / size.Width * 4 - 2, (double) point.Y / size.Height * 4 - 2 );
      Complex z = 0;
      int count = 0;
      do
      {
        z = z * z + c;
        count++;
      }
      while ( z.Magnitude < 4 && count < maxIter );
      return count;
    }
    public static Color ComposeColor( int value )
    {
      double _value;
      if ( value == 0 )
        _value = 0;
      else
        _value = Math.Log( value ) / Math.Log( maxIter );
      return Color.FromArgb( 0xFF, 0, (int) ( Math.Sin( _value * Math.PI ) * 0xFF * 0.75 ), (int) ( ( Math.Sin( _value * Math.PI ) ) * 0xFF ) );
    }
  }
}

1 2  下一页

Tags:曼德 勃罗 特集

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