我正在使用WinForms爲模擬編寫可視化工具。可視化涉及圍繞網格移動的各種對象。是否有可能獲得縮放/翻譯的圖形對象?
到目前爲止,我正在使用擴展Panel的自定義控件,並在Paint事件過程中使用Graphics類進行自定義繪圖。然而,一個令人煩惱的地方是我經常不得不從grid座標縮放到control.DisplayRectangle座標(換句話說,在網格中佔用2個單元格的對象將佔用2 *(control.DisplayRectangle.Width/horizontalGridWidth)繪製時的像素)。
我想知道,有沒有辦法讓圖形對象爲我做這些翻譯,以便我可以在網格座標中表示我的繪圖,並讓它自動映射到物理座標?事實證明,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));
}
}
只要使用Graphics.ScaleTransform()。對ScaleTransform的第二個參數使用帶有負值的TranslateTransform()以反轉座標系並獲取左下角的原點。 –