【发布时间】:2019-03-28 12:37:59
【问题描述】:
我正在创建一个图形表单,其中坐标为 x,y 的对象被绘制到图形中。它适用于小的 x 和 y,但是当我想在不同的位置(例如 x = 500,y = 300)绘制它们时,它们会消失。
public WindowHandler()
{
dc = this.CreateGraphics();
this.Size = new Size(sizeX, sizeY); // 800x600
startSimulation = new Button
{
// button properties
};
this.Controls.Add(startSimulation);
startSimulation.Click += new EventHandler(StartSimulationClick);
}
private void CreationsMethods()
{
creations.PaintAllAnimals(dc);
}
public void PaintAllAnimals(Graphics g)
{
foreach (var animal in ecoStructure.world.animals)
{
animal.PaintAnimal(g);
}
}
public void PaintAnimal(Graphics graphics)
{
Rectangle rectangle = new Rectangle(x, y, 3, 3);
Pen pen = new Pen(colour);
graphics.DrawRectangle(pen, rectangle);
graphics.FillRectangle(colour, rectangle);
}
我想把所有的对象都放到窗口上。有没有办法让图形“更大”?我需要再做一个吗?或者我应该使用不同的工具来绘制矩形?
【问题讨论】:
-
你在哪里画画?
-
我使用我在代码中发布的所有内容。 dc 是 Graphics,我用它来绘制(PaintAnimal 方法)。我也使用
System.Drawing; using System.Windows.Forms; -
看起来像这样:link。如您所见,右侧矩形在中间被“切割”,因为它应该以这个特定的坐标 (x,y) 绘制。它们也应该有更多(总共 15 个),但它们正在从这个图形中删除。
-
问题是你使用了
CreateGraphics,你不应该这样做。 Winform 应用程序中的所有绘制都应在OnPaint覆盖或Paint事件处理程序中完成。下次 Windows 决定重新绘制窗口时,您使用CreateGraphics进行的任何绘制都将被覆盖。顺便说一句,您正在创建一个Pen对象并且永远不会处理它。这是句柄泄漏。 -
好的!非常感谢。我会阅读并更改它。