mgulde
mgulde

Reputation: 215

Monogame sprite alpha blending

At the moment, I am having a 2D grid of terrain textures, which I am drawing using the standard XNA/Monogame spritebatch.Draw() function. In order to have smoother transitions between adjacent but different terrain textures, I would like to blend textures within a certain area (say 3x3) around a center texture. The further a neighboring texture is away, the smaller should be its impact on the final image.

E.g., a (3x3) weighting matrix weight around a central texture at (1,1) could look something like this:

0.3 0.5 0.3
0.5 1.0 0.5
0.3 0.5 0.3

Basically, a simple problem. However, I am currently staggering with the different blending modes offered and their functionality. My initial idea was to just use BlendState.AlphaBlend together with

spriteBatch.Draw(Tex2D, TargetRec, new Color(Color.White, weight[x,y] / SumOfWeights));

The white color should give me the original texture colors, the alpha value weight[x,y] / SumOfWeights would in the end add up to 1. Instead, what I get is a very bright image plus the background shining through.

A better result can be achieved, when also setting the tinting Color to a gray with the same value as the alpha channel. Again, the background is shining through, though, when using more than 2 textures.

There must be a systematic error in my concept, but I am momentarily unable to find it. Please point out my mistake & thanks in advance.

Upvotes: 1

Views: 4095

Answers (1)

Bradley Uffner
Bradley Uffner

Reputation: 16991

Try this:

spriteBatch.Draw(Tex2D, TargetRec, Color.White * weight[x,y]);

This is the proper way to draw things transparently when SpriteBatch is using premultiplication. The alpha channel works differently when drawing with premultiplication. The basic change you need to make is to multiply the color by the transparency instead of setting the alpha channel of the color.

Here is some more information. http://blogs.msdn.com/b/shawnhar/archive/2009/11/06/premultiplied-alpha.aspx

Upvotes: 2

Related Questions