Search code examples
c#collectionsdrawrectangle

How to draw a line of collection of parallelograms


For reasons of aesthetics, I want to create a line composed of parallelograms like this:

enter image description here

But it turns out that the OnPaint override event only allows you to draw rectangles:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Rectangle[] rectangles = new Rectangle[]
    {
         new Rectangle(0, 0, 100, 30),
         new Rectangle(100, 0, 100, 30),
         new Rectangle(200, 0, 100, 30),
         new Rectangle(300, 0, 100, 30),
         new Rectangle(400, 0, 100, 30),
    };

    e.Graphics.DrawRectangles(new Pen(Brushes.Black), rectangles);
}

My problem is that I need to convert the rectangles into parallelograms, and give each one a different color.


Solution

  • The FillPolygon can do the job:

    protected override void OnPaint(PaintEventArgs e) {
      base.OnPaint(e);
      e.Graphics.Clear(Color.White);
    
      int x = 10;
      int y = 10;
      int width = 148;
      int height = 64;
      int lean = 36;
      Color[] colors = new[] { Color.FromArgb(169, 198, 254),
                               Color.FromArgb(226, 112, 112),
                               Color.FromArgb(255, 226, 112),
                               Color.FromArgb(112, 226, 112),
                               Color.FromArgb(165, 142, 170)};
    
      e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
      for (int i = 0; i < colors.Length; ++i) {
        using (SolidBrush br = new SolidBrush(colors[i])) {
          e.Graphics.FillPolygon(br, new Point[] { new Point(x, y),
                                                   new Point(x + lean, y + height),
                                                   new Point(x + lean + width, y + height),
                                                   new Point(x + width, y)});
          x += width;
        }
      }
    }