本人最近才接触 C#编程,老师布置作业:使用 GDI+画圆,半径和颜色都要随机变化,圆要生成若干个。我参考了网上的许多资料,编写了如下代码,但是点击生成按钮,每次仍然只能生成一个圆形。各位会员能够帮我查找一下错误,或者提醒一下?万分感谢!
private void button1_Click(object sender, EventArgs e)
{
Graphics p = this.CreateGraphics();
PaintEventArgs pe = new PaintEventArgs(p, this.ClientRectangle);
panel1_Paint(this, pe);
p.Dispose();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
var list = new List<Rectangle>();
var rand = new Random();
var g = e.Graphics;
int N = 100; //圆的个数
for (int i = 0; i < 1000; i++) //限定最多试探次数,以免出现死循环
{
Random ran = new Random();
int wid = Screen.PrimaryScreen.WorkingArea.Width;
int hei = Screen.PrimaryScreen.WorkingArea.Height;
int R1 = ran.Next(0,1000);
int R2 = ran.Next(0,1000);
int Rnadkey = ran.Next(20, 800);
int Cran1 = ran.Next(0, 255);
int Cran2 = ran.Next(0, 255);
int Cran3 = ran.Next(0, 255);
Brush brush = new SolidBrush(Color.FromArgb(Cran1, Cran2, Cran3));//三原色
var rct = new Rectangle(R1, R2, Rnadkey, Rnadkey);
if ((rct.X + 2 * rct.Width) < wid && (rct.Y + 2 * rct.Width) < hei) //判定是否超出边界
{
list.Add(rct);
g.FillEllipse(brush, rct);
continue;
}
if (--N == 0) break;
}
}
1
stupidcat 2015-10-27 20:31:20 +08:00
将
Graphics p; 定义为成员变量,将 p = this.CreateGraphics(); 放在这个 Form 的构造函数里 |
2
stupidcat 2015-10-27 20:42:50 +08:00
务必无视上面这条。。
|
3
abelyao 2015-10-27 20:47:52 +08:00
1. 圆形可否叠加?
2. 圆形可否超出画布范围? 如果都不要求… 那不就是随便画吗… |
4
stupidcat 2015-10-27 20:54:28 +08:00 1
private void button1_Click(object sender, EventArgs e)
{ Graphics p = this.CreateGraphics(); PaintEventArgs pe = new PaintEventArgs(p, this.ClientRectangle); panel1_Paint(this, pe); p.Dispose(); } private void panel1_Paint(object sender, PaintEventArgs e) { var g = e.Graphics; var ran = new Random(); int N = 10; //圆的个数 while(true) { int R1 = ran.Next(0, this.Width); int R2 = ran.Next(0, this.Height); int Randkey = ran.Next(10, 200); if (R1 + Randkey < this.Width && R2 + Randkey < this.Height) //判定是否超出边界 { var rct = new Rectangle(R1, R2, Randkey, Randkey); int Cran1 = ran.Next(0, 255); int Cran2 = ran.Next(0, 255); int Cran3 = ran.Next(0, 255); Brush brush = new SolidBrush(Color.FromArgb(Cran1, Cran2, Cran3));//三原色 Pen pen = new Pen(brush); g.DrawEllipse(pen, rct); if (--N == 0) { break; } } } } |
5
xbb7766 2015-10-27 21:53:00 +08:00
4 楼正解
|
6
ElegantOfKing OP @abelyao 是的,随便画......
|
7
ElegantOfKing OP @stupidcat 万分感谢!有了您的代码,加上昨天自己的修改,已经完全符合老师的要求了。
|