日期:2014-05-18 浏览次数:20912 次
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
Point center, oldCenter, dragStart;
GraphicsPath path;
int scale = 100;
public Form1()
{
this.Size = new Size(600, 400);
center = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
path = GeneratePath();
}
// 根据计算好的控制点绘制分形
protected override void OnPaint(PaintEventArgs e)
{
using (Graphics g = e.Graphics)
{
g.DrawPath(Pens.Red, path);
}
this.Text = string.Format("center: {0,3},{1,3} scale: {2}", center.X, center.Y, scale);
}
// 用滚轮控制放大缩小
protected override void OnMouseWheel(MouseEventArgs e)
{
scale = scale + e.Delta / 4;
scale = Math.Min(10000, scale);
scale = Math.Max(10, scale);
path = GeneratePath();
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
dragStart = e.Location;
oldCenter = center;
this.Capture = true;
}
protected override void OnMouseUp(MouseEventArgs e)
{
this.Capture = false;
}
// 用鼠标移动图形
protected override void OnMouseMove(MouseEventArgs e)
{
if (this.Capture)
{
center = Point.Add(oldCenter, new Size(e.X - dragStart.X, e.Y - dragStart.Y));
path = GeneratePath();
Invalidate();
}
}
// 创建图形的控制点
GraphicsPath GeneratePath()
{
byte[] types = new byte[this.ClientSize.Width];
for (int i = 0; i < types.Length; i++) types[i] = (byte)PathPointType.Line;
PointF[] samples = new PointF[types.Length];
for (int x = 0; x < samples.Length; x++)
{
// 只画屏幕中看得到的x点。30.0f用来减缓频率以美观图形
samples[x].X = x;
samples[x].Y = Sinc((x - center.X) / (scale / 30.0f)) * scale + center.Y;
}
return new GraphicsPath(samples, types);
}
static float Sinc(float theta)
{