[PR]
[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
プログラミング、3DCGとその他いろいろについて
[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
ここでは画像ファイルをウィンドウに表示します。
外部のファイルをあつかうには、ContentManagerを使います。
これは、画像ファイルや3Dモデル、フォントなどをゲームにロードするときに使います。
なお、このクラスを使うときには、XNA Game Studioの助けがないと地獄を見ます。
というのも、それらのファイル一つ一つに対応するxnbファイルを作らなければならないからです。
(しかもこいつはバイナリファイルです)
例えば、image.jpgというファイルを直接使うことはできません。
"image.xnb"というファイルを"image.jpg"から作って、それを使わなければならないのです。
XNA Game Studioはそれを自動で行ってくれます。
このことを全く気にする必要はありません。
ただ"image.jpg"ファイルをソリューションエクスプローラーのコンテントにペーストするだけでいいのです。
以下がXNA Game Studioでビルドしたコードです。
(Mainメソッドは別のクラスに移動しました)
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; class MyGame : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D texture; public MyGame() { graphics = new GraphicsDeviceManager(this); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); texture = Content.Load<Texture2D>("Content/Penguins"); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(texture, new Rectangle(0, 0, 200, 150), Color.White); spriteBatch.End(); } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; class MyGame : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D texture; public MyGame() { graphics = new GraphicsDeviceManager(this); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); texture = new Texture2D(GraphicsDevice, 1, 1); texture.SetData<Color>(new Color[] { Color.Black }); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), Color.White); spriteBatch.End(); } static void Main() { using (MyGame game = new MyGame()) { game.Run(); } } }
texture = new Texture2D(GraphicsDevice, 3, 1); texture.SetData<Color>(new Color[] { Color.Navy, Color.White, Color.Red });
spriteBatch.Begin(); spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), Color.White); spriteBatch.Draw(texture, new Rectangle(200, 200, 80, 80), Color.White); spriteBatch.End();
前回では、ウィンドウが全く描画を行っていませんでした。
そのため、XP以前の環境だと他のウィンドウに隠されると跡が残ってたいへん見苦しいものでした。
これではいけません!
このような跡はすぐに消せるようにならなければなりません。
それが出来るようになったのが、以下のコードです:
using Microsoft.Xna.Framework; class MyGame : Game { GraphicsDeviceManager graphics; public MyGame() { graphics = new GraphicsDeviceManager(this); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); } static void Main() { using (MyGame game = new MyGame()) { game.Run(); } } }
class MyGame : Microsoft.Xna.Framework.Game { static void Main() { using (MyGame game = new MyGame()) { game.Run(); } } }