在MonoGame中绘制矩形

Evo*_*lor 3 c# geometry rectangles drawrectangle monogame

如何在MonoGame中绘制形状,例如矩形和圆形,而不必在"内容"文件夹中保存预先绘制的形状?

DrawRectangle()和DrawEllipse()适用于Windows窗体,不适用于我正在使用的OpenGL.

Ayb*_*ybe 10

编辑

你可以通过GitHub上的教程学习MonoGame的基本知识:https://github.com/aybe/MonoGameSamples


使用3D基元和2D投影

这是一个简单的解释示例

我定义了一个10x10矩形并设置了世界矩阵,使其看起来像2D投影:

注意:这BasicEffect是绘制原语的原因

protected override void LoadContent()
{
    _vertexPositionColors = new[]
    {
        new VertexPositionColor(new Vector3(0, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 10, 1), Color.White),
        new VertexPositionColor(new Vector3(0, 10, 1), Color.White)
    };
    _basicEffect = new BasicEffect(GraphicsDevice);
    _basicEffect.World = Matrix.CreateOrthographicOffCenter(
        0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
}
Run Code Online (Sandbox Code Playgroud)

然后我绘制了整个事物:D

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    EffectTechnique effectTechnique = _basicEffect.Techniques[0];
    EffectPassCollection effectPassCollection = effectTechnique.Passes;
    foreach (EffectPass pass in effectPassCollection)
    {
        pass.Apply();
        GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, _vertexPositionColors, 0, 4);
    }
    base.Draw(gameTime);
}
Run Code Online (Sandbox Code Playgroud)

你有你的矩形!

在此输入图像描述

现在这只是冰山一角,

或者正如上面其中一篇文章中提到的那样,你可以使用一个着色器代替它...

我需要在前一段时间绘制一个超级椭圆并最终草绘这个着色器:

在HLSL中绘制SuperEllipse

正如你在帖子中看到的那样,Superellipse不仅可以绘制椭圆,还可以绘制其他形状甚至圆形(我没有测试过),所以你可能对它感兴趣.

最终你会想要一些类/方法来隐藏所有这些细节,所以你只需要调用类似的东西DrawCircle().

提示:通过发布@ https://gamedev.stackexchange.com/,您可能会获得有关Monogame相关问题的更多答案

:d


小智 6

如果您需要在2D中创建一个矩形,您可以这样做:

 Color[] data = new Color[rectangle.Width * rectangle.Height];
 Texture2D rectTexture = new Texture2D(GraphicsDevice, rectangle.Width, rectangle.Height);

 for (int i = 0; i < data.Length; ++i) 
      data[i] = Color.White;

 rectTexture.SetData(data);
 var position = new Vector2(rectangle.Left, rectangle.Top);

 spriteBatch.Draw(rectTexture, position, Color.White);
Run Code Online (Sandbox Code Playgroud)

在某些情况下,可能比Aybe的回答容易一点.这会创建一个实心矩形.