基於Visual C#的DirectX開發例項——繪製一個三角形
通過Direct3D繪製的每個物件都是有三角形組成的,一個三角形由三個點組成,而每個點都定義成一個向量來指定點的X、Y和Z座標。DirectX中有一種定義頂點的結構,那就是CustomVertex類,只需要在渲染函式中新增類似如下程式碼即可繪製一個三角形:
CustomVertex.TransformedColored[] vertices = new CustomVertex.TransformedColored[3];//定義頂點
vertices[0].Position = new Vector4(150f, 400f, 0f, 1f);
vertices[0].Color = Color.Red.ToArgb();
vertices[1].Position = new Vector4(this.Width / 2 , 100f, 0f, 1f);
vertices[1].Color = Color.Green.ToArgb();
vertices[2].Position = new Vector4(this.Width-150f, 400f, 0f, 1f);
vertices[2].Color = Color.Yellow.ToArgb();
其中第一行程式碼為建立一個數組,用於表示三個頂點的資訊。TransformedColored表示頂點座標為平面座標且各點都具有顏色,剩下的程式碼為頂點設定座標和顏色。下面的程式碼將告訴
device.VertexFormat = CustomVertex.TransformedColored.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertices);
第二句程式碼實際上是繪製三角形的程式碼,函式DrawUserPrimitives()的第一個引數表示頂點資料為列表形式,如果要繪製四個三角形則前面定義的頂點陣列vertices有12個頂點。第二個引數為要繪製的三角形的數目。這段程式碼要置於device.BeginScene()和device.EndScene()