我正在使用 WinForms 为模拟编写可视化工具。可视化涉及围绕网格移动的各种对象。
到目前为止,我正在使用扩展 Panel 的自定义控件,并在 Paint 事件期间使用 Graphics 类进行自定义绘图。然而,一个令人恼火的是,我经常不得不从网格坐标缩放到 control.DisplayRectangle 坐标(换句话说,在网格中占用 2 个单元格的对象将占用 2 * (control.DisplayRectangle.Width /绘制时的水平网格宽度)像素)。
我想知道,有没有办法让 Graphics 对象为我做这些翻译,以便我可以在网格坐标中表达我的绘图并让它自动映射到物理坐标?
事实证明 Matrix 确实是关键(见接受的答案)。这是使它工作的代码:
public SimulationPanel() {
this.DoubleBuffered = true;
this.SizeChanged += (o, e) => this.Invalidate();
this.Paint += this.PaintPanel;
}
private void Paint(object sender, PaintEventArgs e) {
e.Graphics.Clear(Color.Black);
var fromRectangle = GetSimulationWorldCoordinates();
var toRectangle = ScaleToFit(fromRectangle, this.DisplayRectangle);
using (var matrix = new Matrix(
fromRectangle,
new[] {
toRectangle.Location,
new Point(toRectangle.Right, toRectangle.Top),
new Point(toRectangle.Left, toRectangle.Bottom),
}))
{
// draw the simulation stuff here using simulation coordinates
e.Graphics.Transform = matrix;
e.Graphics.FillRectangle(Brushes.LightBlue, toRectangle);
e.Graphics.DrawLine(Pens.Red, toRectangle.Location, new Point(toRectangle.Right, toRectangle.Bottom));
}
}