Xna提供的Window虽然基本够用,但有时需要将图形绘制到别的控件上,如做编辑器等.
下面是非常简洁的代码,很容易看懂.
1.Game类
2.Program类
3.测试类
呵呵,思路:利用GraphicsDevice.present(ControlHandler)方法,改变渲染目标为ControlHandler而非Window.
另外可参考:http://shiba.hpe.sh.cn/jiaoyanzu/wuli/ShowArticle.aspx?articleId=714&classId=4
下面是非常简洁的代码,很容易看懂.
1.Game类
/// <summary>
/// 普通的Game类
/// </summary>
public partial class FormGame:Game{
GraphicsDeviceManager graphics;
public FormGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
//获取Window的Form的引用
gameForm = (Form)Form.FromHandle(Window.Handle);
gameForm.Shown += new EventHandler(gameForm_Shown);
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
//查看是否切换显示到WinForm
if (winForm != null)
{
GraphicsDevice.Present(winForm.Handle);
}
}
void gameForm_Shown(object sender, EventArgs e)
{
if (winForm != null)
{
winForm.Show();
gameForm.Hide();
}
}
}
/// <summary>
/// 处理winForm的Game
/// </summary>
public partial class FormGame : Game
{
Form winForm;
Form gameForm;
public FormGame(Form winForm)
: this()
{
this.winForm = winForm;
winForm.FormClosing += new FormClosingEventHandler(winForm_FormClosing);
winForm.Resize += new EventHandler(winForm_Resize);
}
void winForm_Resize(object sender, EventArgs e)
{
if (winForm == sender)
{
graphics.PreferredBackBufferWidth = winForm.Width;
graphics.PreferredBackBufferHeight = winForm.Height;
graphics.ApplyChanges();
}
}
void winForm_FormClosing(object sender, FormClosingEventArgs e)
{
Exit();
}
}
2.Program类
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
Form1 f = new Form1();
using (FormGameTest test = new FormGameTest(f))
{
test.Run();
}
}
}
3.测试类
class FormGameTest : FormGame
{
SpriteBatch spriteBatch;
Texture2D texture;
public FormGameTest(Form form):base(form)
{
}
protected override void LoadContent()
{
base.LoadContent();
texture = Content.Load<Texture2D>("5");
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(texture, new Rectangle(0, 0, 400, 300), Color.Red);
spriteBatch.End();
base.Draw(gameTime);
}
}
呵呵,思路:利用GraphicsDevice.present(ControlHandler)方法,改变渲染目标为ControlHandler而非Window.
另外可参考:http://shiba.hpe.sh.cn/jiaoyanzu/wuli/ShowArticle.aspx?articleId=714&classId=4