如何在输出屏幕上画直线

此为原创,转载请注明作者和出处,谢谢!

如题,如何在输出屏幕上画出形状,如矩形,3角形,直线等。。

此类的开发不能在Content通道中加入材质帖图,而是用3维的点画出2点的位置,然后用语句相连,与

前段时间的2D游戏开发,用帖图的方式有了很大的区别

首先新建一个XNA3。0的项目。保留声明的代码如:

GraphicsDeviceManager graphics;  //系统生成时自带的

然后在下面添加如下代码:

 private BasicEffect effect;  //基本效果

private VertexDeclaration vd;  //材质声明

在Game1()这个构造函数中添加代码用于初始化

gdm = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
gdm.PreferredBackBufferWidth = 1280; //设置BUFFER的宽,也是游戏屏幕的宽高
gdm.PreferredBackBufferHeight = 720;  //设置BUFFER的高

其中GraphicDeviceManager()方法要在写出来

public GraphicsDeviceManager GetGraphicsDeviceManager()
{
            return gdm;
}

我曾经试图简写红色的代码,甚至去掉,发现程序总报错,看来这段代码很关键!

在Draw()方法中添加画直线的方法:

public void DrawLine(float x0, float y0, float x1, float y1)
{
            float cw = gdm.PreferredBackBufferWidth / 2; //屏幕的中点
            float ch = gdm.PreferredBackBufferHeight / 2; //屏幕的中点
            effect.Begin();  //效果开始运用
            gdm.GraphicsDevice.VertexDeclaration = vd;//不详但很重要
            VertexPositionColor[] v = new VertexPositionColor[2];//材质的位置点数组,如果画别的形状,可以扩展这些点
            v[0] = new VertexPositionColor(new Vector3(-1f + x0 / cw, 1f - y0 / ch, 0), color);
            v[1] = new VertexPositionColor(new Vector3(-1f + x1 / cw, 1f - y1 / ch, 0), color);
            foreach (EffectPass pass in effect.CurrentTechnique.Passes)  //遍历pass
            {
                pass.Begin();
                gdm.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(
                    PrimitiveType.LineList, v, 0, 1);//在设备上画点变成线
                pass.End();
            }
            effect.End();
}

//上面的方法可以随便布置直线的方位

 public void DrawUserPrimitives<T> (
         PrimitiveType primitiveType,
         T[] vertexData,
         int vertexOffset,
         int primitiveCount
)

primitiveType  描述材质的类型
vertexData    空间点的数据
vertexOffset   最高点的偏移量
primitiveCount  绘画出的数量,

原文地址:https://www.cnblogs.com/315358525/p/1503009.html