How to make part of sprite transparent at runtime?

Hi, I’m new to Monogame.
I want to make transparent a part of a sprite, in execution time.
I have my sprite in a RenderTarget2D.
I have tried to draw another totally transparent sprite on top, but of course that does not work.
spriteBatch.Draw(trans6x20, Vector2.Zero, Color.TransparentBlack);

trans6x20 is a texture2d, The file was created with Paint an all pixels set tocolor (255,0,255) and saved as BMP.

Is there any easy way to do it?


I think I have made some progress, now I can make a 6x20 rectangle transparent:
Color[] pixels = new Color[escudo.Width * escudo.Height];
for (int x = (int)posRelativa.X; x < posRelativa.X+6; x++)
for (int y = (int)posRelativa.Y ; y < posRelativa.Y+20; y++)
pixels[x + y * escudo.Width] = Color.Transparent;

But it’s not exactly what I want.

I want to be able to draw a texture (for example, a white circle with a transparent background) on another texture and make it look like the circle is transparent.

I hope your help. Thank you very much.

If you set BlendState to BlendState.Opaque in your SpriteBatch.Begin call it will overwrite the rendertarget data with your texture.

Thank you very much Jjagg.

With your answer, part of the problem is solved. Now I can make transparent a rectangle of a sprite using another fully transparent sprite.

But I need to know how I can make a circle of a sprite transparent using another sprite that has a drawn circle. I just want to make transparent the corresponding part of that circle in the first sprite.

Thank you.

To those who are interested in the subject, I copy the code to draw a transparent rectangle on a sprite:
escudo = Content.Load(“base”);
//create the transparent rectangle.
trans= new RenderTarget2D(GraphicsDevice, 6, 20);
//create the sprite on which I will draw transparent rectangles.
escudoActual = new RenderTarget2D(GraphicsDevice, escudo.Width, escudo.Height,false,this.GraphicsDevice.PresentationParameters.BackBufferFormat,
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
spriteBatch.Draw(escudo, Vector2.Zero, Color.White);
//Draw the transparent rectangle
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
spriteBatch.Draw(trans, new Vector2(10 + escudo.Width / 2, 10), Color.White);

Oh of course that won’t work, sorry I glossed over this a bit quickly :sweat_smile:

One way to achieve what you want is with the built-in AlphaTestEffect. I’ll set up a quick sample project :slight_smile:

Here’s a gist with the Game1 file:
Hope that helps! :slight_smile:

EDIT: By the way, like it’s implemented now, the texture I use to clip the circle out needs to have an alpha value of 0 where the circle is. If you’re using that texture for something else, or want to render it by itself that’s probably not very useful. If that’s the case, let me know. We can solve it by using the stencil buffer or a custom shader.

Hi Jjagg, it’s exactly what I was looking for. Many thanks.

1 Like