Yoone
Yoone

Reputation: 549

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?

Upvotes: 3

Views: 1350

Answers (1)

Andrew Russell
Andrew Russell

Reputation: 27225

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).

Upvotes: 4

Related Questions