开发一个界面,能够按某种要求随机出现图案
大家好,我是研一的,刚接触C#,老师要求做一个界面,当外界串口满足某种需求时界面上出现一个图标,再次满足要求时界面上又出现一个图标,我想知道这种随机图标的出现怎么实现?有看到说是GDI?谢谢大家
2012-11-21 21:32
2012-11-21 22:18
程序代码:using System;
using using System.Drawing;
using System.Windows.Forms;
namespace RandomImage
{
public partial class RandomImager : Control
{
#region 构造函数
public RandomImager()
{
InitializeComponent();
RectanglePercent = .2;
}
#endregion
#region 公共属性
[Category("Custom")]
public double RectanglePercent { get; set; }
#endregion
#region 公共方法
public void Rebuild()
{
var g = CreateGraphics();
var flags = new bool[Width][];
for (var i = 0; i < Width; i++) flags[i] = new bool[Height];
var pointCount = 0;
var totalPixel = (double)Width * Height;
var random = new Random(DateTime.Now.Millisecond);
g.Clear(BackColor);
while (true)
{
var point = new Point(random.Next(0, Width), random.Next(0, Height));
if (flags[point.X][point.Y]) continue;
var brush =
new SolidBrush(Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255),
random.Next(0, 255)));
g.FillRectangle(brush, point.X, point.Y, random.Next(1, 30), random.Next(1, 30));
flags[point.X][point.Y] = true;
pointCount++;
if (pointCount / totalPixel < RectanglePercent) continue;
break;
}
}
#endregion
#region 重写方法
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
#endregion
}
}
程序代码:using System.Windows.Forms;
using Timer = System.Threading.Timer;
namespace RandomImage
{
public partial class FormMain : Form
{
#region 全局字段
private Timer _timer;
#endregion
#region 构造函数
public FormMain()
{
InitializeComponent();
Ri.Rebuild();
_timer = new Timer(TimerProcess, null, 1000, 1000);
}
#endregion
#region 事件处理
private void TimerProcess(object o)
{
Ri.Rebuild();
}
#endregion
}
}
程序代码:namespace RandomImage
{
partial class FormMain
{
private components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.Ri = new RandomImage.RandomImager();
this.SuspendLayout();
this.Ri.Dock = System.Windows.Forms.DockStyle.Fill;
this.Ri.Location = new System.Drawing.Point(0, 0);
this.Ri.Name = "Ri";
this.Ri.RectanglePercent = 0.01D;
this.Ri.Size = new System.Drawing.Size(335, 191);
this.Ri.TabIndex = 0;
this.Ri.Text = "randomImager1";
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(335, 191);
this.Controls.Add(this.Ri);
this.Name = "FormMain";
this.ShowIcon = false;
this.Text = "Random Image by ";
this.ResumeLayout(false);
}
private RandomImager Ri;
}
}

2012-11-21 22:55
2012-11-26 10:24
2012-11-26 18:33