Creating a shader to draw outside of a texture/sprite font

Hello everyone,

I am studying shaders to be able to create new few effects.
What I could understand so far that we have 2 possibilities of shaders: You can make a shader only for you texture or for everything.

The problem is that creating a shader for a texture I can only change the pixel color, and I would like to create an effect that is bigger than the size of the texture.
eg: Let’s say that I need to create a border of a texture (ignoring the alpha)

How can I create a shader to process pixels that are outside of my texture (for example 2px of margin)

Thank you,
Danilo Peres

Look into render targets. You could draw your texture into a rt. Then use the rt as texture and apply a shader on it.

1 Like

Yeap, exactly…

It looks like that I need create a render target first…


For who is looking an example:

public static Texture2D ImgWIthMargin(GraphicsDevice graphicsDevice, Texture2D img, int margin)
    // crate a render target with margins
    var renderTarget = new RenderTarget2D(graphicsDevice, img.Width + margin * 2, img.Height + margin * 2);


        using (SpriteBatch spriteBatch = new SpriteBatch(graphicsDevice))
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null);

            // draw the texture with the margin
            spriteBatch.Draw(img, new Vector2(margin), Color.White);


    return renderTarget;

and now you can apply the effect to the new image

var img = ImgWIthMargin(GraphicsDevice, myImage, 10);
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, myEffect);
spriteBatch.Draw(img, new Vector2(0, 0), Color.White);
1 Like

You know, you could skip the shader pass entirely on this. If all y ou’re doing is a solid outline colour, just change graphicsDevice.Clear(Color.Transparent) to graphicsDevice.Clear(someOutlineColour). I think that should work…


Not really for 2 reasons.

  1. If I paint all the background with a color, when I draw a texture with transparent pixels it will get the background color.
  2. The solid color border was only an example, the goal is to be able to use those pixels for shader processing (for Bloom, Outline, Shadow or whatever effect that we need to apply)

Anyway thanks for the idea…

Ah, yea that totally wouldn’t work then. I thought you just wanted a rectangular border :slight_smile:

1 Like