DrawTriangle.cs
上传用户:lslight
上传日期:2022-01-10
资源大小:14248k
文件大小:4k
- ////////////////////////////////////////////////////////////////////////
- // ■■■■ ■■■■■ ■■■■ ■ ■ //
- // ■ ■ ■ ■ ■ //
- // ■ ■ ■ ■■■ ■ ■ //
- // ■ ■ ■ ■ ■ ■ //
- // ■■■■ ■ ■■■■ ■■■■ //
- // Copyright (c) 三峡大学水利与环境学院 肖泽云. All rights reserved. //
- ////////////////////////////////////////////////////////////////////////
- using System;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Windows.Forms;
- using Microsoft.DirectX;
- using Microsoft.DirectX.Direct3D;
- namespace 绘制一个三角形
- {
- public partial class DrawTriangle : Form
- {
- Device device = null;//定义绘图设备
- public DrawTriangle()
- {
- this.ClientSize = new Size(800, 600);//指定窗体尺寸
- this.Text = "绘制一个三角形";//指定窗体标题
- }
- public bool InitializeDirect3D()
- {
- try
- {
- PresentParameters presentParams = new PresentParameters();
- presentParams.Windowed = true; //指定以Windows窗体形式显示
- presentParams.SwapEffect = SwapEffect.Discard; //当前屏幕绘制后它将自动从内存中删除
- device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); //实例化device对象
- return true;
- }
- catch (DirectXException e)
- {
- MessageBox.Show(e.ToString(), "Error"); //处理异常
- return false;
- }
- }
- public void Render()
- {
- if (device == null) //如果device为空则不渲染
- {
- return;
- }
- device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0); //清除windows界面为深蓝色
- device.BeginScene();
- //在此添加渲染图形代码
- 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();
- device.VertexFormat = CustomVertex.TransformedColored.Format;
- device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertices);
- device.EndScene();
- device.Present();
- }
- static void Main()
- {
- DrawTriangle DrawTriangle = new DrawTriangle(); //创建窗体对象
- if (DrawTriangle.InitializeDirect3D() == false) //检查Direct3D是否启动
- {
- MessageBox.Show("无法启动Direct3D!", "错误!");
- return;
- }
- DrawTriangle.Show(); //如果一切都初始化成功,则显示窗体
- while (DrawTriangle.Created) //设置一个循环用于实时更新渲染状态
- {
- DrawTriangle.Render(); //保持device渲染,直到程序结束
- Application.DoEvents(); //处理键盘鼠标等输入事件
- }
- }
- }
- }