[英]Drawing a rectangle in C#
This is a very simple question but I couldn't find anything on the internet that was helpful.这是一个非常简单的问题,但我在互联网上找不到任何有用的信息。 Basically, I am trying to draw a rectangle but when I launch my code nothing is happening (I don't have any errors either).
基本上,我正在尝试绘制一个矩形,但是当我启动我的代码时什么也没有发生(我也没有任何错误)。 Here is the code:
这是代码:
class Buildings
{
public void test(Game1 mainGame, SpriteBatch spriteBatch)
{
var buildingrect = new Rectangle(mainGame.bufferHeight - 30, 50, 200, 50);
// (Note: mainGame.alien2 is a texture I have - this isn't the problem)
spriteBatch.Draw(mainGame.alien2, buildingrect, Color.White);
}
}
public class Game1 : Microsoft.Xna.Framework.Game
{
protected override void Draw(GameTime gameTime)
{
buildings.test(this, spriteBatch);
}
}
Thank you for your help and I apologize again for this being such a simple question - I'm still a beginner.感谢您的帮助,我再次为这个如此简单的问题道歉——我还是个初学者。
Unfortunately, you can not draw rectangles simple like that.不幸的是,您不能像那样简单地绘制矩形。 You can solve it like this:
你可以这样解决:
Create a texture that holds the pixelcolor for the rectangle创建一个包含矩形像素颜色的纹理
private Texture2D pixel;
private Rectangle rect; //your rectangle`
Initialize it with your preferred color:用你喜欢的颜色初始化它:
pixel = new Texture2D(GraphicsDevice, 1, 1);
pixel.SetData(new[] { Color.White });`
In your draw
method you now draw each side of your rectangle:在您的
draw
方法中,您现在绘制矩形的每一边:
int bw = 2; // Border width
//Left
spriteBatch.Draw(pixel, new Rectangle(rect.Left, rect.Top, bw, rect.Height), Color.Black);
//Right
spriteBatch.Draw(pixel, new Rectangle(rect.Right, rect.Top, bw, rect.Height), Color.Black);
//Top
spriteBatch.Draw(pixel, new Rectangle(rect.Left, rect.Top, rect.Width, bw), Color.Black);
//Bottom
spriteBatch.Draw(pixel, new Rectangle(rect.Left, rect.Bottom, rect.Width, bw), Color.Black);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.