我输入正确我所有的矩形垂直堆叠,每次绘制一个新的矩形时都有不同的颜色,但我很难让输出看起来像底部的图片。请任何人帮助我走正确的道路。
//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);
}
答案 0 :(得分:2)
对于每个矩形,订购最短到最高,
每当你创建一个水平矩形时,将它放在下面(就水平位置而言)你正在创建的水平矩形的顶部。