我在c#中製作了一個基本的窗口化遊戲,我無法爲屏幕創建基本的位圖。我在屏幕面板,並且我希望能夠吸引到它,所以我用下面的代碼:C#位圖 - 參數無效
public partial class GameWIndow : Form
{
public GameWIndow()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Bitmap buffer;
buffer = new Bitmap(Width, Height);
Task.Factory.StartNew(() =>
{
using (Graphics g = Graphics.FromImage(buffer))
{
g.FillRectangle(new SolidBrush(Color.PaleGoldenrod), 10, 10, 100, 100);
}
this.Invoke(new Action(() =>
{
this.BackgroundImage = buffer;
}));
});
}
當這個運行時,它給我的錯誤「參數無效」爲線
buffer = new Bitmap(Width, Height);
寬度和高度分別是900和700,都是整數。
如果問題是我這樣做完全錯了,那麼更好的方法來實現這一點。
-------- -------編輯
我看過您的意見,似乎是我在上面所做的是非常可怕的,所以我嘗試了不同的方法,和我不確定這是否更好。
private Game game;
private Thread renderThread;
private Stopwatch stopwatch = new Stopwatch();
public GameWindow()
{
InitializeComponent();
//Starts game
game = new Game();
//Starts rendering
this.DoubleBuffered = true;
renderThread = new Thread(new ThreadStart(draw));
renderThread.Start();
}
//Runs when screen is asked to refresh
private void panel1_Paint(object sender, PaintEventArgs e)
{
//Sends graphics to game class where it draws game
game.draw(e.Graphics);
}
private void draw()
{
stopwatch.Start();
while (true)
{
//If 1/60th of a sec has passed
if (stopwatch.ElapsedMilliseconds > 1000D/60D)
{
stopwatch.Restart();
Invalidate();
}
}
}
上面的代碼不能正常運行,我不太清楚爲什麼,如果有人可以提供幫助的,我對此表示讚賞。然而,我的主要問題不是如何解決這個問題,但如果這是一個有效的或「正確的」繪製方式。
這個問題很可能是你完全錯誤的。我不知道爲什麼你會得到這個錯誤,但是禁止從其它線程修改GUI。 (仔細閱讀,這絕對不是你得到這個錯誤的原因,但該規則仍然適用。) – adv12
你想做什麼?這看起來有點可疑。 'PaintEventArgs'已經包含了你應該繪製的'Graphics'的一個實例。 – vcsjones
如果您爲該控件啓用了雙緩衝樣式,則只需以最直接的方式編寫「Paint」事件處理代碼即可。 –