如何使用GDI填充18*18方格的外围边界为黑色?
实现18×18方格外围边界填充黑色
我已经绘制出一个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(); } }
解决方案
要实现外围边界填充黑色,需要调整代码的绘图逻辑,同时修复原代码中CreateGraphics()导致的绘图丢失问题:
- 改用Paint事件的Graphics对象:
panel.CreateGraphics()绘制的内容会在控件刷新时消失,必须使用PaintEventArgs提供的e.Graphics来绘图,保证内容持久化。 - 填充外围边界区域:用
SolidBrush绘制并填充网格的外围边界,或者用粗Pen绘制外框(根据需求选择)。
修改后的完整代码:
public partial class Form1 : Form { private int XTILES = 25; private int YTILES = 25; private int TILELOCATION = 20; private readonly Pen _gridPen = new Pen(Color.Black); private readonly SolidBrush _borderBrush = new SolidBrush(Color.Black); public Form1() { InitializeComponent(); } private void DrawBoard(Graphics g) { // 绘制18×18网格线 for (int i = 0; i < 19; i++) { g.DrawLine(_gridPen, TILELOCATION + i * XTILES, TILELOCATION, TILELOCATION + i * XTILES, TILELOCATION + 18 * XTILES); g.DrawLine(_gridPen, TILELOCATION, TILELOCATION + i * YTILES, TILELOCATION + 18 * YTILES, TILELOCATION + i * YTILES); } // 定义边界宽度,可按需调整 int borderWidth = 3; int totalGridWidth = 18 * XTILES; int totalGridHeight = 18 * YTILES; // 填充四个方向的外围边界 // 顶部 g.FillRectangle(_borderBrush, TILELOCATION, TILELOCATION - borderWidth, totalGridWidth + XTILES, borderWidth); // 底部 g.FillRectangle(_borderBrush, TILELOCATION, TILELOCATION + totalGridHeight, totalGridWidth + XTILES, borderWidth); // 左侧 g.FillRectangle(_borderBrush, TILELOCATION - borderWidth, TILELOCATION, borderWidth, totalGridHeight + YTILES); // 右侧 g.FillRectangle(_borderBrush, TILELOCATION + totalGridWidth, TILELOCATION, borderWidth, totalGridHeight + YTILES); // 若需求是加粗外框而非填充区域,可替换为以下代码: // using var borderPen = new Pen(Color.Black, borderWidth); // g.DrawRectangle(borderPen, TILELOCATION - borderWidth/2, TILELOCATION - borderWidth/2, totalGridWidth + XTILES, totalGridHeight + YTILES); } private void panel_Paint(object sender, PaintEventArgs e) { base.OnPaint(e); DrawBoard(e.Graphics); } // 释放GDI资源,避免内存泄漏 protected override void Dispose(bool disposing) { if (disposing) { _gridPen.Dispose(); _borderBrush.Dispose(); components?.Dispose(); } base.Dispose(disposing); } }
关键说明
- 用
readonly修饰绘图对象,确保只初始化一次,并在Dispose中释放资源,避免GDI对象泄漏。 - 填充边界时,通过计算网格的总尺寸和偏移量,确保边界完全覆盖网格的外围。
- 两种实现方式可选:填充区域适合需要实心边界的场景,粗Pen绘制外框适合需要边框线条的场景。
内容的提问来源于stack exchange,提问作者toe ko
相关产品推荐
相关产品推荐

