我正在尝试制作一个随机地形生成器。目前,我正在使用Windows Forms Graphics来绘制所有内容。我似乎无法使引擎工作。运行以下代码不会在窗体上显示任何内容,即使它应该绘制一个从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;
}
}
}
答案 0 :(得分:1)
这很有效!感谢TyCobb的快速回答。
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
{
Engine e;
public Form1()
{
InitializeComponent();
e = new Engine(100, 100);
e.Color3(Color.Blue);
e.fRect(new Rectangle(0,0,50,50));
}
protected override void OnPaint(PaintEventArgs pe)
{
// Call the OnPaint method of the base class.
base.OnPaint(pe);
pe.Graphics.DrawImage(e.getBuffer(), 1, 1, 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;
}
}
}
我覆盖了表单的OnPaint事件,该事件每帧重绘一次矩形。问题是表单是在矩形上绘画。 How to use the OnPaint event in C#?