In WP7 XNA game, how do I create a semi-transparent rectangle on screen as a notification message box?

message, transparent, xna

Solution

Andy's solution will suffice, but it might take a few tries until you find the transparency you're after and it also involves creating and loading a new resource in your program. Fortunately you can avoid this and can make the process configurable by generating a single transparent pixel at runtime which will stretch to the bounds of the `Rectangle` argument in the `SpriteBatch.Draw(Texture2D, Rectangle, Nullable<Rectangle>, Color)` call:

//You can probably turn this in to a re-useable method
Byte transparency_amount = 100; //0 transparent; 255 opaque
Texture2D texture = new Texture2D(Device,1,1,false,SurfaceFormat.Color);
Color[] c = new Color[1];
c[0] = Color.FromNonPreMultiplied(255,255,255,transparency_amount);
texture.SetData<Color>(c);

Now use the new `texture` variable in your draw call.

As for multi-line text, there is a `SpriteBatch.DrawString()` overload that accepts a StringBuilder argument. Meaning you can in theory go:

//configure
StringBuilder sb = new StringBuilder();
sb.AppendLine("First line of text");
sb.AppendLine("Second line of text");

//draw
SpriteBatch.DrawString(font, sb, position, Color.White);

I'll give you another hint that will help you determine the size of the drawing rectangle for the texture:

//spits out a vector2 *size* of the multiline text
Vector2 measurements = font.MeasureString(sb); //works with StringBuilder

You can then create a `Rectangle` from this information, and even give it some padding:

Rectangle rectangle = new Rectangle(window_x, window_y, (int)measurements.X, (int)measurements.Y);
rectangle.Inflate(5); //pad by 5 pixels

Then put everything in to the draw call, including what color to draw the window

SpriteBatch.Draw (texture, rectangle, Color.Black); //draw window first
SpriteBatch.DrawString(font, sb, position, Color.GreenYellow); //draw text second

The result is a little nicer looking, more automated, and configurable. You should be able to wrap all this stuff in to a re-usable configurable class for your notification messages.

Note: anything other than drawing code should be in LoadContent() or somewhere else, not the actual game's Draw() call.

Pardon any syntactical errors, I've just wrote it off the top of my head.. :)

Problem

Is it possible to create a transparent messagebox (rectangle) that can write multiple-line text on it?

Original source