การโหลด Texture
ไปที่ folder Content คลิกขวาเลือก Add->Existing Item แล้วก็ browse ไปหาไฟล์ภาพ
หลังจากได้ภาพมาแล้วก็เขียนโค้ด โดยจะใช้คลาส Texture2D เพื่อนำภาพมาทำเป็น texture
ดังนี้
Texture2D txt2d;
จากนั้นในเมธอด LoadContent() ก็เขียนคำสั่งเพื่อโหลดรูปภาพดังนี้
txt2d = Content.Load<Texture2D>("water"); // water เป็นชื่อไฟล์(ไม่ต้องมี extension)
พอโหลดเสร็จแล้วต่อไปที่ต้องทำก็คือ การวาด รูปภาพลงไปในหน้าจอ ซึ่งในการวาดรูปภาพนี้จะใช้
object ของคลาส SpriteBatch
ให้ไปที่เมธอด Draw แล้วเขียนโค้ดดังนี้
spriteBatch.Begin();
spriteBatch.Draw(txt2d,new Rectangle(0,0,1000,1000), Color.White);
spriteBatch.End();
ผลลัพธ์ดังรูป

ตัวอย่างโค้ด Game1.cs
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace WindowsGame4
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D txt2d;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
txt2d = Content.Load<Texture2D>("water");
// TODO: use this.Content to load your game content here
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(txt2d,new Rectangle(0,0,1000,1000), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
[With great power comes great responsibility]