Question

I need to create a 40x40 matrix and color each cell manually like below.

Color Matrix

I think that i can make it with 40*40=160 labels on a form application and color them one by one but it isn't very effective. What's the best practice for this. Maybe ColorMatrix?

Was it helpful?

Solution

This is a complete, but simple, Windows Forms app.

This is probably the most straight forward way. Consider the fact that I'm not grabbing the colors from a matrix, but you get the idea, it has the way you should paint it in the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

            for (int x = 0, y = 0; x + y != (this.Width + this.Height); x++)
            {
                var color = Color.Red;
                if (x % 2 == 0 && y % 2 != 0) { color = Color.Blue; }

                e.Graphics.FillRectangle(new SolidBrush(color), x, y, 1, 1);

                if (x == this.Width)
                {
                    x = -1;
                    y++;
                }
            }
        }
    }
}

OTHER TIPS

One alternative to intercepting the OnPaint event would be to create a Bitmap of 40x40 Pixels e.g. via the System.Drawing.Bitmap class, set all the Pixels' colors.

Finally display it depending on your UI technology in a PictureBox (Windows Forms) or Image (WPF) with a scaling value set to fill out the whole control's size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top