说明:此示例不考虑性能,应付作业也足够了,真正实用的话还要考虑性能问题,需要很多技巧的;
自定义控件ACircle
程序代码:using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace RandomCircle
{
public partial class ACircle : Control
{
#region 只读全局字段
private readonly Brush _brush;
#endregion
#region 构造函数
public ACircle(int id)
{
InitializeComponent();
ID = id;
_brush = new SolidBrush(Color.Goldenrod);
Draw();
}
#endregion
#region 公共属性
public int ID { get; set; }
#endregion
#region 重写方法
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Draw();
}
#endregion
private void Draw()
{
var g = CreateGraphics();
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.FillEllipse(_brush, ClientRectangle);
}
}
}
FormMain.cs
程序代码:using System;
using System.Drawing;
using System.Windows.Forms;
using Timer = System.Threading.Timer;
namespace RandomCircle
{
delegate void AddCircleEventHandler(Point point);
public partial class FormMain : Form
{
#region 常量
private const int CircleSize = 30;
#endregion
#region 只读全局字段
private readonly Timer _timer;
#endregion
#region 全局字段
private int _id;
#endregion
#region 构造函数
public FormMain()
{
InitializeComponent();
_timer = new Timer(TimerProcess, null, 2000, 2000);
}
#endregion
#region 控件事件
void newACircle_Click(object sender, EventArgs e)
{
var aCircle = (ACircle) sender;
Text = string.Concat("Random Circle by mmxo - ", aCircle.ID);
}
#endregion
#region 事件处理
private void TimerProcess(object o)
{
var random = new Random(DateTime.Now.Millisecond);
_timer.Change(random.Next(1000, 3000), 0);
var location = new Point(random.Next(0, ClientSize.Width - CircleSize),
random.Next(0, ClientSize.Height - CircleSize));
while (true)
{
var newACircleClientRectangle = new Rectangle(location.X, location.Y, CircleSize, CircleSize);
var locationValid = true;
foreach (Control control in Controls)
{
if (!(control is ACircle)) continue;
var aCircle = (ACircle) control;
var rect = new Rectangle(aCircle.Location, new Size(CircleSize, CircleSize));
if (!rect.IntersectsWith(newACircleClientRectangle)) continue;
locationValid = false;
break;
}
if (!locationValid) continue;
break;
}
AddCircle(location);
}
private void AddCircle(Point point)
{
if (InvokeRequired)
Invoke(new AddCircleEventHandler(AddCircle), new object[] { point });
else
{
var newACircle = new ACircle(++_id) { Location = point, Width = CircleSize, Height = CircleSize };
newACircle.Click += newACircle_Click;
Controls.Add(newACircle);
}
}
#endregion
}
}








