我的输入正确完成,我的所有矩形都垂直堆叠,每次绘制新矩形时都有不同的颜色,但我很难让输出看起来像底部图片。请任何人都可以帮助我走上正确的道路。
//List to strore all randomly generated rectangles
List<Rectangle> rectangleCollection = new List<Rectangle>();
//Counts the amount of time a rectangle needs to be drawn
int count = 0;
public static Random ran = new Random();
void CreateRectangle()
{
int TallestRectangle = 0; ;
int PrevRecY = 0;
Graphics graphic = pictureBox1.CreateGraphics();
SolidBrush brush;
foreach (Rectangle rect in rectangleCollection)
{
if (rect.Height > TallestRectangle)
TallestRectangle = rect.Height;
}
foreach (Rectangle rect in rectangleCollection)
{
graphic.FillRectangle(brush = new SolidBrush(Color.FromArgb(ran.Next(1, 255), ran.Next(1, 255), ran.Next(1, 255))),
new Rectangle(rect.X + PrevRecY, (TallestRectangle - rect.Height), rect.Width, rect.Height));
PrevRecY += rect.Width;
}
}
private void button1_Click(object sender, EventArgs e)
{
count = int.Parse(textBox1.Text);
for (int i = 0; i < count; i++)
{
GetRandomRectangle();
}
CreateRectangle();
}
void GetRandomRectangle()
{
Graphics graph = this.CreateGraphics();
int x = 0;
int y = 0;
int width = ran.Next(20, 100);
int height = ran.Next(30, 150);
Rectangle rec1 = new Rectangle(x, y, width, height);
rectangleCollection.Add(rec1);
}