在WP7 XNA游戏中,如何在屏幕上创建一个半透明矩形作为通知消息框?

ths*_*ieh 2 xna message transparent

是否可以创建一个可以在其上写入多行文本的透明消息框(矩形)?

kal*_*tec 9

Andy的解决方案就足够了,但是在您找到所需的透明度之前可能需要几次尝试,它还涉及在程序中创建和加载新资源.幸运的是,您可以避免这种情况,并且可以通过在运行时生成单个透明像素来使进程可配置,该像素将延伸到调用中Rectangle参数的边界SpriteBatch.Draw(Texture2D, Rectangle, Nullable<Rectangle>, Color):

//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);
Run Code Online (Sandbox Code Playgroud)

现在texture在绘制调用中使用新变量.

对于多行文本,有一个SpriteBatch.DrawString()接受StringBuilder参数的重载.理论上你可以说:

//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);
Run Code Online (Sandbox Code Playgroud)

我会给你另一个提示,帮助你确定纹理的绘图矩形的大小:

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

然后,您可以从此信息创建一个Rectangle,甚至给它一些填充:

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

然后将所有内容都放入绘制调用中,包括绘制窗口的颜色

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

结果是更好看,更自动化和可配置.您应该能够将所有这些内容包装到可重复使用的可配置类中,以用于通知消息.

注意:绘图代码以外的任何内容都应该在LoadContent()或其他地方,而不是实际游戏的Draw()调用.

原谅任何语法错误,我只是把它写在我的头顶.. :)