2

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

4

2 回答 2

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

现在在您的绘图调用中使用新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);

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

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

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

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

然后把所有东西都放到draw call中,包括绘制窗口的颜色

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

结果看起来更好看、更自动化和可配置。您应该能够将所有这些东西包装到一个可重用的可配置类中,用于通知消息。

注意:除了绘图代码之外的任何东西都应该在 LoadContent() 或其他地方,而不是实际游戏的 Draw() 调用。

请原谅任何语法错误,我只是把它写在我的脑海里.. :)

于 2012-05-29T21:12:29.707 回答
2

在诸如 Paint.NET(免费)之类的东西中创建一个纹理,允许您编辑颜色的 alpha 值。

将纹理的一小部分区域设置为白色,alpha 值类似于 255,255,255,100 (r,g,b,a),下图在红色正方形内有您需要的内容,尽管它没有明显显示在白色上。

白方块

现在使用SpriteBatch.Draw,您可以将纹理绘制到屏幕上,它会显示您在纹理中设置的 alpha 值。

// Texture2D is a reference to the texture from above.
// Rectangle is the screen rectangle you want to draw your grey box at.
// Nullable<Rectangle> is the location of the white data inside the red box.
// Color is the colour that you want your grey box to be (grey?)
SpriteBatch.Draw (Texture2D, Rectangle, Nullable<Rectangle>, Color)

使用 SpriteFont 覆盖您想要的文本。

于 2012-05-29T14:29:37.890 回答