简体   繁体   中英

C# Monogame - premultiplied alpha

I need a fade effect for transition between my screens. I've read online that old method for alpha blending from XNA 3 is deprecated and XNA 4's premultiplied alpha should be used. So I'm using Monogame and I assume the code would be the same but can you explain more about this premultiplied alpha? Also a code example compatible with my own code would be great! Here's some of it:

// Variables
private Texture2D image;
private Vector2 imagePosition;
private Color startColour;
private Color endColour;
private float alpha;

// Constructor
public myClass()
{
    startColour = new Color(0.0f, 0.0f, 0.0f, 0.0f);
    endColour = new Color(255.0f, 255.0f, 255.0f, 255.0f);
    alpha = 0.0f;
}

// Update method
public void Update(GameTime gameTime)
{
    // ??????
}

// Draw method
public void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Begin();
    spriteBatch.Draw(image, imagePos, startColour * alpha); // ???
    spriteBatch.End();
}

I believe most of the code is there but I still need to update the alpha, change it from 0 to 1, or is that how you fade from white? I want to fade from white to opaque. So how do you do this? What code should I have in my Update() method and how should I change my current code?

This should be quite simple, if I understand right that you're trying to go from white to nothing.

public myClass()
{
    ...
    alpha = 1.0f; // I'm almost sure that 1 means solid
}    

public void Update(GameTime gameTime)
{
    if (alpha > 0.0f) alpha -= 0.01f;
}

Take into account that Update() is called every frame, that means 60 times per second by default (in current monogame version), so you have to adjust the decimal position of the 0.01f to make it as fast as you want.

Also you can just go with Color.White * alpha in spriteBatch.draw . And you need to call the drawing of everything that is to appear before (above) the drawing of the "curtain".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM