示例:绘制2.5D地图网格辅助线
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestGraphics
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawMapGrid(e.Graphics, 8, 6, 64, 32);
}
private void Form1_Load(object sender, EventArgs e)
{
//当窗口尺寸改变时重绘所有窗口
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
}
private void DrawMapGrid(Graphics g, Rectangle mapRect, int gridWidth, int gridHeight)
{
int rowCount = mapRect.Height / gridHeight;
int colCount = mapRect.Width / gridWidth;
DrawMapGrid(g, rowCount, colCount, gridWidth, gridHeight);
}
private void DrawMapGrid(Graphics g, int rowCount, int colCount, int gridWidth, int gridHeight)
{
Pen pen = new Pen(Brushes.Black);
Point p1;
Point p2;
List<Point> vertexs = CalMapVertexs(g, rowCount, colCount, gridWidth, gridHeight);
int maxVertIndex = vertexs.Count - 1;
//绘制斜线
for (int i = 0; i < colCount + rowCount; i++)
{
p1 = vertexs[i];
p2 = vertexs[maxVertIndex - i];
g.DrawLine(pen, p1, p2);
}
//绘制反斜线
int index1 = colCount - 1;
int index2 = colCount;
for (int i = 0; i < colCount + rowCount; i++)
{
int startIndex = index1 - i;
if (startIndex < 0)
startIndex += vertexs.Count;
p1 = vertexs[startIndex];
p2 = vertexs[index2 + i];
g.DrawLine(pen, p1, p2);
}
}
private List<Point> CalMapVertexs(Graphics g, int rowCount, int colCount, int gridWidth, int gridHeight)
{
Pen pen = new Pen(Brushes.Black);
Point p = new Point(gridWidth / 2, 0);
List<Point> vertexs = new List<Point>();
//计算上边顶点坐标
for (int i = 0; i < colCount; i++)
{
g.DrawEllipse(pen, p.X, p.Y, 5, 5);
vertexs.Add(new Point(p.X, p.Y));
p.X += gridWidth;
}
//计算右侧顶点坐标
p.X -= gridWidth / 2;
p.Y = gridHeight / 2;
for (int i = 0; i < rowCount; i++)
{
g.DrawEllipse(pen, p.X, p.Y, 5, 5);
vertexs.Add(new Point(p.X, p.Y));
p.Y += gridHeight;
}
//计算下边顶点坐标
p.X -= gridWidth / 2;
p.Y -= gridHeight / 2;
for (int i = 0; i < colCount; i++)
{
g.DrawEllipse(pen, p.X, p.Y, 5, 5);
vertexs.Add(new Point(p.X, p.Y));
p.X -= gridWidth;
}
//计算左侧坐标
p.X = 0;
p.Y -= gridHeight / 2;
for (int i = 0; i < rowCount; i++)
{
g.DrawEllipse(pen, p.X, p.Y, 5, 5);
vertexs.Add(new Point(p.X, p.Y));
p.Y -= gridHeight;
}
return vertexs;
}
}
}
运行效果