Search code examples
c#xnaxna-4.0texture2d

How to check if a Texture2D is transparent?


I want to check if the selected rectangle is transparent:

spriteBatch.Draw(texture, new Vector2(0, 0), 
           new Rectangle(0, 0, 16, 16), Color.White);

Is it possible?


Solution

  • Yes, it is possible. You have to check all the pixels in the region are transparent. Note that this is a fairly slow operation.

    Here is a method that should do what you want:

    bool IsRegionTransparent(Texture2D texture, Rectangle r)
    {
        int size = r.Width * r.Height;
        Color[] buffer = new Color[size];
        texture.GetData(0, r, buffer, 0, size);
        return buffer.All(c => c == Color.Transparent);
    }
    

    Note that I haven't compiled, tested or optimised the above. Also, it's designed for premultiplied textures (the default in XNA 4.0).