toe ko
toe ko

Reputation: 88

I'd like to fill up the color of the square using GDI

enter image description here

I made a square of 18*18 now. I'd like to fill the first boundary of the square with black color like in the picture,

what should I do?

  public partial class Form1 : Form
{
    private int XTILES = 25;
    private int YTILES = 25;
    private int TILELOCATION = 20;
    Graphics g;
    Pen pen;
 
    public Form1()
    {
        InitializeComponent();
        pen = new Pen(Color.Black);        
    }

    private void DrawBoard()
    {
        g = panel.CreateGraphics();
        for(int i = 0; i < 19; i++)
        {
            g.DrawLine(pen, new Point(TILELOCATION + i * XTILES, TILELOCATION),
                new Point(TILELOCATION + i * XTILES, TILELOCATION + 18 * XTILES));

            g.DrawLine(pen, new Point(TILELOCATION, TILELOCATION + i * YTILES),
               new Point(TILELOCATION + 18 * YTILES, TILELOCATION + i * YTILES));
        }
    }
    private void panel_Paint(object sender, PaintEventArgs e)
    {
        base.OnPaint(e);
        DrawBoard();
    }
}

Upvotes: 0

Views: 164

Answers (1)

Jiri Volejnik
Jiri Volejnik

Reputation: 1089

There are many ways. Here is one of them: Draw top, left, right and bottom edges separately using FillRect.

    Brush brush = new SolidBrush(Color.Black);

    private void panel_Paint(object? sender, PaintEventArgs e)
    {
        DrawBoundary(e.Graphics);
    }

    void DrawBoundary(Graphics g)
    {
        g.FillRectangle(brush, ToGraphics(new Rectangle(0, 0, XTILES, 1)));
        g.FillRectangle(brush, ToGraphics(new Rectangle(XTILES - 1, 0, 1, YTILES)));
        g.FillRectangle(brush, ToGraphics(new Rectangle(0, YTILES - 1, XTILES, 1)));
        g.FillRectangle(brush, ToGraphics(new Rectangle(0, 0, 1, YTILES - 1)));
    }

    public Rectangle ToGraphics(Rectangle r)
    {
        return new Rectangle(TILELOCATION + r.X * TILESIZE, TILELOCATION + r.Y * TILESIZE, r.Width * TILESIZE, r.Height * TILESIZE);
    }

[ADDED- see comments]:

    void DrawBoard(Graphics g)
    {
        for (int i = 0; i <= XTILES; i++)
            g.DrawLine(pen, 
                new Point(TILELOCATION + i * TILESIZE, TILELOCATION),
                new Point(TILELOCATION + i * TILESIZE, TILELOCATION + YTILES * TILESIZE - 1));

        for (int i = 0; i <= YTILES; i++)
            g.DrawLine(pen, 
                new Point(TILELOCATION, TILELOCATION + i * TILESIZE),
                new Point(TILELOCATION + XTILES * TILESIZE - 1, TILELOCATION + i * TILESIZE));
    }

Upvotes: 1

Related Questions