寬度要 10n + 1 才能畫 n + 1 條線
C# WinForm Code
- PicutreBox:用來繪製格線
- ComboBox:設定 PictureBox 長寬
namespace GraphicsNETSample
{
public partial class frmGridLine : Form
{
private int _cellLength { get; init; } = 50;
private Pen _gridLine { get; init; } = new Pen(Color.Black, 1);
private int _gridSizeInit { get; set; } = 500;
public frmGridLine()
{
InitializeComponent();
comboBox1.Items.Add(_gridSizeInit);
comboBox1.Items.Add(501);
comboBox1.SelectedIndex = comboBox1.FindStringExact(_gridSizeInit.ToString());
SetPictureBoxSize(_gridSizeInit);
}
private void SetPictureBoxSize(int size)
{
pictureBox1.Width = size;
pictureBox1.Height = size;
}
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
int size = Convert.ToInt32(comboBox1.Text);
SetPictureBoxSize(size);
pictureBox1.Refresh();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
DrawGridLine(e.Graphics);
}
private void DrawGridLine(Graphics g)
{
RectangleF bound = g.ClipBounds;
int boundWidth = (int)bound.Width;
int boundHeight = (int)bound.Height;
for (Point topLeft = new Point(0, 0); topLeft.Y <= boundHeight; topLeft.Offset(0, _cellLength))
g.DrawLine(_gridLine, topLeft, new Point(boundWidth, topLeft.Y));
for (Point topLeft = new Point(0, 0); topLeft.X <= boundWidth; topLeft.Offset(_cellLength, 0))
g.DrawLine(_gridLine, topLeft, new Point(topLeft.X, boundWidth));
}
}
}
執行效果
- 延伸閱讀
- [C#] 繪圖 - 九宮格
- 參考資料
- Point.Offset 方法
沒有留言:
張貼留言