winforms 我想使用GDI填充方块的颜色

pu82cl6c  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(284)

我现在做了一个18*18的正方形。我想用黑色填充正方形的第一个边界,就像图片中一样,

我该怎么办?

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();
    }
}
ev7lccsx

ev7lccsx1#

方法有很多,下面是其中之一:使用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);
    }

[添加-参见备注]:

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));
    }

相关问题