編輯:這不是「如何在C#中使用OnPaint事件」的重複,因爲我甚至不知道它存在。當我不知道答案時,我在問一個問題。這就像問我「我怎麼檢查我車裏的油」,當我甚至不知道浸漬棒是什麼。請刪除重複標誌,如果這樣做可以解釋爲什麼它不是重複的。爲什麼在構造函數的窗體上繪製不在窗體上顯示任何東西?
我想製作一個隨機地形生成器。目前,我正在使用Windows Forms圖形繪製所有圖形。我似乎無法讓引擎工作。運行下面的代碼不會在窗體上顯示任何內容,即使它應該從0,0到50,50繪製一個黑色的矩形。誰能解決?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Random_Terrain_Generator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Engine e = new Engine(100, 100);
e.Color3(Color.Blue);
e.rect(new Rectangle(0,0,50,50));
Graphics fg = this.CreateGraphics();
fg.DrawImage(e.getBuffer(), 1, 100, 100, 100);
}
}
public class Engine
{
Color fillColor;
Bitmap buffer;
Graphics bufferGraphics;
public Engine(int bufferWidth, int bufferHeight)
{
buffer = new Bitmap(bufferWidth, bufferHeight);
bufferGraphics = Graphics.FromImage(buffer);
}
public void fRect(Rectangle r)
{
bufferGraphics.FillRectangle(new SolidBrush(fillColor), r);
}
public void rect(Rectangle r)
{
bufferGraphics.DrawRectangle(new Pen(fillColor), r);
}
public void Color3(Color c)
{
fillColor = c;
}
public Bitmap getBuffer()
{
return buffer;
}
}
}
你在窗體構造函數中做了所有事情。一旦表格畫出來,你的盒子就不見了。當感覺需要更新時,表單會不斷重新繪製。這意味着你每次都需要畫畫。 http://stackoverflow.com/questions/10076116/how-to-use-the-onpaint-event-in-c – TyCobb
它會幫助,如果我把它放在表單加載事件?我正在做initializeConponent之後,所以我會假設它會在窗體後面繪製。 –
不,你必須重寫OnPaint方法,因此當它完成繪畫時,可以在它上面繪畫。看看我鏈接的例子。 – TyCobb