Xna将图形绘制到WinForm控件

Xna提供的Window虽然基本够用,但有时需要将图形绘制到别的控件上,如做编辑器等.
下面是非常简洁的代码,很容易看懂.
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gamebox1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值