Saturday, October 17, 2015

xna - How can I remove Magic Pink from an image at runtime using GraphicsDevice?


In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb)


Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method:


enter image description here


How can I turn it into a Texture2D object and convert the pink to be transparent using GraphicsDevice? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card.




Answer



I would imagine a custom pixel Shader for the SpriteBatch would be the fastest method here.


Using something like this:


// WARNING! UNTESTED CODE FOLLOWS
void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0,
inout float4 position : POSITION0)
{
if (color == float4(1, 1, 0, 1)
color = float4(0, 0, 0, 0)
}


In a custom effect passed to your SpriteBatches Begin() method, it should make every pixel with an ARGB value of OxFFFF00FF transparent while keeping any pixel with a different color the same.


I haven't done much work with 2d shaders apart from Post Processing effects, so I'm not exactly sure what values you'll need to pass to Begin() to get transparency working correctly.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...