因为主要是贴代码,代码来自以下连接的Blog。所以类别就选成转载了。
因为数目比较庞大(4096),计算速度十分缓慢,大概需要十多分钟。有需要的可自行修改代码。
通过控制台后台生成图片的,大家可进一步完善到Windows Forms Application。
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(@"D:\C#\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));
}
}
}
效果图如下: