As long as the XBox 360 supports the Texture2D.SetData method and basic file I/O, you can load textures dynamically. You must read the .bmp file data, convert its pixel data to an ARGB format and store it in a managed byte array. Then, you just pass the byte array to the Texture2D.SetData method and you're done.
The following code copies data from a System.Drawing.Bitmap into a Texture2D, using the Texture2D.SetData method. While the System.Drawing.Bitmap class is not supported on the XBox 360, this code simply demonstrates that as long as you can get a managed byte array containing your bitmap data in an ARGB format, you can copy the data into a texture with the SetData method.
| //Returns a Texture2D containing the same image as the bitmap parameter, resized if necessary. Returns null if an error occurs. |
| public Texture2D CreateTextureFromBitmap( GraphicsDevice graphics_device, System.Drawing.Bitmap bitmap ) |
| { |
| Texture2D texture = null; |
| bool dispose_bitmap = false; |
| try |
| { |
| if (bitmap != null) |
| { |
| //Resize the bitmap if necessary, then capture its final size |
| if (graphics_device.GraphicsDeviceCapabilities.TextureCapabilities.RequiresPower2) |
| { |
|
System.Drawing.Size new_size; //New size will be next largest power of two, so bitmap will always be scaled up, never down
|
| new_size = new Size( (int)Math.Pow( 2.0, Math.Ceiling( Math.Log( (double)bitmap.Width ) / Math.Log( 2.0 ) ) ), (int)Math.Pow( 2.0, Math.Ceiling( Math.Log( (double)bitmap.Height ) / Math.Log( 2.0 ) ) ) ); |
| bitmap = new Bitmap( bitmap, new_size ); |
| dispose_bitmap = true; |
| } |
| System.Drawing.Size bitmap_size = bitmap.Size; |
| |
| //Create a texture with an appropriate format |
| texture = new Texture2D( graphics_device, bitmap_size.Width, bitmap_size.Height, 1, TextureUsage.None, SurfaceFormat.Color ); |
| |
| //Lock the bitmap data and copy it out to a byte array |
| System.Drawing.Imaging.BitmapData bmpdata = bitmap.LockBits( new System.Drawing.Rectangle( 0, 0, bitmap_size.Width, bitmap_size.Height ), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); |
| byte [ ] pixel_bytes = null; |
| try |
| { |
| pixel_bytes = new byte[bmpdata.Stride * bmpdata.Height]; |
| Marshal.Copy( bmpdata.Scan0, pixel_bytes, 0, temp_bytes.Length ); |
| }catch{} //If error occurs allocating memory, bitmap will still be unlocked properly |
| bitmap.UnlockBits( bmpdata ); |
| |
| //Set the texture's data to the byte array containing the bitmap data that was just copied |
| if (pixel_bytes != null) texture.SetData<byte>( pixel_bytes ); |
| } |
| } |
| catch |
| { |
| //Error occured; existing texture must be considered invalid |
| if (texture != null) |
| { |
| texture.Dispose(); |
| texture = null; |
| } |
| } |
| finally |
| { |
| if (dispose_bitmap) |
| bitmap.Dispose(); |
| } |
| return texture; |
| } |