XNA draw / paint onto a Texture2D at runtime
Asked Answered
K

1

11

Morning all (if its morning where you are)

I have been looking around and have not seen a satisfactory method for doing this so thought I would ask around...

Ideal world I would like to be able to generate a transparent Texture2D object. Drawing this to the screen I would like to be able to "paint" to it, i.e. when the left mouse button is down whatever pixel the cursor is over should be set to black. Following this I would then need to be able to use this texture.

Using the texture is the easy part, we can simply make a new Texture2D attribute for a "painting" object and use that in the SpriteBatch.Draw method. The two tricky parts are

  1. Generating a texture2D object of a specified size, filled with transparency in code.
  2. Editing that texture2D on the fly (i.e. being able to alter pixel colours)

If anyone has any experience of these you input would be very much appreciated.

Kurth answered 20/7, 2011 at 7:51 Comment(0)
S
14

You can either use a RenderTarget2D (MSDN), which is itself a Texture2D (so you can use it in SpriteBatch.Draw). This allows you to render onto a texture in the same way you render onto the screen. You need to use GraphicsDevice.SetRenderTarget (MSDN) to set this up.

Or you can use Texture2D.SetData (MSDN) to manipulate pixels directly. You can construct a transparent Texture2D directly (MSDN). Don't forget to Dispose of any textures or other resources you create yourself!

Steamroller answered 20/7, 2011 at 8:6 Comment(2)
Brilliant, thanks Andrew you helpful response is really appreciated! Ill boot up VS and do a mock-up as soon as I get the chance, ill report back, hopefully with some sample code for anyone else strolling across this question.Kurth
if you don't mind, I happen to be strolling very carefully over this questionExcommunicatory

© 2022 - 2024 — McMap. All rights reserved.