テクスチャの部分描画
著者:
赤坂玲音
公開日:
元のテクスチャの特定の長方形領域だけを切り抜いて描画する方法を解説します。
テクスチャの切り抜き
元のテクスチャの一部分だけを切り抜いてスプライトを描画することも可能です。テクスチャの一部だけを描画するには、描画するテクスチャの範囲を Rectangle の Null 可能型で指定します。 第 3 パラメータの sourceRectangle 以外は、これまでの Draw() メソッドと同じです。
SpriteBatch クラス Draw() メソッド
public void Draw ( Texture2D texture, Vector2 position, Nullable<Rectangle> sourceRectangle, Color color )
public void Draw ( Texture2D texture, Rectangle destinationRectangle, Nullable<Rectangle> sourceRectangle, Color color )
texture パラメータには、描画するテクスチャを指定します。Vector2 型の position パラメータを指定した場合は、伸縮なしで指定した座標にスプライトを描画し、Rectangle 型の destinationRectangle パラメータを指定した場合は、スプライトを指定した領域に伸縮して描画します。重要なのは、次の sourceRectangle パラメータです。ここに、元のテクスチャのから描画する範囲を指定します。このパラメータに null を渡した場合、テクスチャ全体が描画されます。color パラメータには、合成する色を指定します。
コード1
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; public class TestGame : Game { public static void Main(string[] args) { using (Game game = new TestGame()) game.Run(); } private GraphicsDeviceManager graphicsDeviceManager; private SpriteBatch sprite; private Texture2D texture; private Rectangle sourceRectangle; public TestGame() { graphicsDeviceManager = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; sourceRectangle = new Rectangle(50, 50, 200, 150); } protected override void LoadContent() { sprite = new SpriteBatch(GraphicsDevice); texture = Content.Load<Texture2D>("TestImage"); base.LoadContent(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); sprite.Begin(); sprite.Draw(texture, Vector2.Zero, sourceRectangle, Color.White); sprite.End(); base.Draw(gameTime); } }
実行結果
コード1は、元のテクスチャから一部分だけを切り抜いてスプライトを描画しています。第 2 パラメータには Vector2 型の座標を渡しているため、伸縮は行われず、切り抜いたテクスチャの領域がそのままのサイズで描画されます。第 2 パラメータに Rectangle 型を渡せば、切り抜いたテクスチャを伸縮して描画できます。