天天看點

c# 3d圖像顯示

1.應用directx圖形庫進行開發;

2.代碼:

public class TClass : System.Windows.Forms.Form
    {
        /// <summary>
        /// 裝置對象,場景中所有圖形對象的父對象
        /// </summary>
        private Device device = null;

        /// <summary>
        /// 坐标系四棱錐頂點緩沖
        /// </summary>
        VertexBuffer vertexBuffer = null;

        /// <summary>
        /// 此參數設定為必須,它定義了要建立的Direct3D裝置的表示參數,如背景緩沖區的高度、寬度和像素格式、如何從背景緩沖區複制到前台緩存、以及螢幕顯示的方式等等
        /// </summary>
        PresentParameters presentParameters;

        /// <summary>
        /// 暫停标志
        /// </summary>
        bool pause = false;

        /// <summary>
        /// 随機數,用來生成随機顔色用的
        /// </summary>
        Random rn = new Random();

        /// <summary>
        /// 構造函數,設定窗體大小
        /// </summary>
        public TClass()
        {
            this.ClientSize = new System.Drawing.Size(300, 300);
        }

        /// <summary>
        /// 初始化繪圖環境
        /// </summary>
        /// <returns></returns>
        public bool InitializeGraphics()
        {
            try
            {
                presentParameters = new PresentParameters();
                //設定螢幕顯示模式為視窗模式
                presentParameters.Windowed = true;
                //設定如何從背景緩沖區複制到前台緩沖區(SwapEffect.Discard表示緩沖區在顯示後立即被舍棄,這樣可以節省開銷)
                presentParameters.SwapEffect = SwapEffect.Discard;
                //建立一個裝置
                device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParameters);
                //為裝置釋放訂閱事件處理
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);

                this.OnCreateDevice(device, null);
                this.OnResetDevice(device, null);
                pause = false;
                return true;
            }

            catch (DirectXException)
            {
                return false;
            }
        }

        /// <summary>
        /// 裝置建立時建立頂點緩沖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;

            //建立頂點緩沖,有個頂點
            vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 18, dev, 0, CustomVertex.PositionColored.Format, Pool.Default);
            //為建立頂點緩存訂閱事件處理
            vertexBuffer.Created += new System.EventHandler(this.OnCreateVertexBuffer);

            this.OnCreateVertexBuffer(vertexBuffer, null);
        }


        /// <summary>
        /// 裝置撤銷的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnResetDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;
            //關閉剔除模式,使我們能看見此四棱錐的前面和後面
            dev.RenderState.CullMode = Cull.None;
            // 關閉場景裡的燈光,顯示頂點自己的顔色
            dev.RenderState.Lighting = false;
        }

        /// <summary>
        /// 建立頂點緩存的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateVertexBuffer(object sender, EventArgs e)
        {

            VertexBuffer vb = (VertexBuffer)sender;
            CustomVertex.PositionColored[] verts = (CustomVertex.PositionColored[])vb.Lock(0, 0);

            //四棱錐原始的個點
            Vector3 vertex1 = new Vector3(25, 0, 0);
            Vector3 vertex2 = new Vector3(0, 0, -25);
            Vector3 vertex3 = new Vector3(-25, 0, 0);
            Vector3 vertex4 = new Vector3(0, 0, 25);
            Vector3 vertex5 = new Vector3(0, 25, 0);

            //四棱錐中包含個三角形,是以要構造個點來繪制
            verts[0].Position = vertex1;
            verts[1].Position = vertex2;
            verts[2].Position = vertex5;
            verts[3].Position = vertex2;
            verts[4].Position = vertex3;
            verts[5].Position = vertex5;
            verts[6].Position = vertex3;
            verts[7].Position = vertex4;
            verts[8].Position = vertex5;
            verts[9].Position = vertex4;
            verts[10].Position = vertex1;
            verts[11].Position = vertex5;
            verts[12].Position = vertex2;
            verts[13].Position = vertex1;
            verts[14].Position = vertex3;
            verts[15].Position = vertex3;
            verts[16].Position = vertex1;
            verts[17].Position = vertex4;


            //給每個點賦予随機顔色
            for (int i = 0; i < 18; i++)
            {
                verts[i].Color = Color.FromArgb(SetColor(), SetColor(), SetColor()).ToArgb();

            }
            vb.Unlock();



        }

        /// <summary>
        /// 傳回到之間的一個随機數,用來生成随機顔色
        /// </summary>
        /// <returns></returns>
        public int SetColor()
        {
            int number = rn.Next(256);
            return number;
        }


        /// <summary>
        /// 設定錄影機的位置
        /// </summary>
        private void SetupCamera()
        {
            //設定世界矩陣,根據系統運作時間而變化
            device.Transform.World = Matrix.RotationAxis(new Vector3((float)Math.Cos(Environment.TickCount / 250.0f), 1, (float)Math.Sin(Environment.TickCount / 250.0f)), Environment.TickCount / 3000.0f);
            //設定錄影機的位置,它在z軸上-50處,看着原點,y軸為正方向
            device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f, 0.0f, -50f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f));

            //設定錄影機的視界,角度為度,看的最近為,看的最遠處為.不再這個視界中的影像都不會被顯示
            device.Transform.Projection = Matrix.PerspectiveFovLH(((float)(float)Math.PI / 2), 1.0f, 10.0f, 200.0f);
        }


        /// <summary>
        /// 繪制圖形
        /// </summary>
        public void Render()
        {
            if (device == null)
                return;

            if (pause)
                return;

            //背景設為綠色
            device.Clear(ClearFlags.Target, System.Drawing.Color.Blue, 1.0f, 0);
            //開始場景
            device.BeginScene();
            // 設定世界,視野和投影矩陣
            SetupCamera();

            // 給裝置指定頂點緩存
            device.SetStreamSource(0, vertexBuffer, 0);

            //設定裝置的頂點格式
            device.VertexFormat = CustomVertex.PositionColored.Format;

            //繪制圖形,使用的方法為三角形清單,個數為個
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 6);

            //結束場景
            device.EndScene();

            //更新場景
            device.Present();
        }

        //重載OnPaint函數
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //繪制圖形
            this.Render();
        }
    }
      

  調用代碼:

using (TClass frm = new TClass())
            {
                if (!frm.InitializeGraphics()) // 初始化 Direct3D
                {
                    MessageBox.Show("不能初始化 Direct3D.程式将退出.");
                    return;
                }
                frm.Show();

                // While the form is still valid, render and process messages
                while (frm.Created)
                {
                    frm.Render();
                    Application.DoEvents(); //處理目前在消息隊列中的所有 Windows 消息
                }
            }
      

  3.需要引用directx的程式集,下載下傳連接配接(含項目):

  連結:https://pan.baidu.com/s/1D4wrHC7c2Pg1wpWXlrLrSA

  提取碼:7f6w

  4.注意調用Microsoft.DirectX.dll時候,需要在程式配置檔案中設定useLegacyV2RuntimeActivationPolicy為true。