这里我们介绍最基础的知识,首先我们想要在计算机上进行图像显示,我们首先需要一个​​GUI​​​界面。因此本篇主要介绍如何使用​​OpenTK​​​创建​​GUI​​界面。

  1. 创建主程序中的类
using OpenTK.Mathematics;
using OpenTK.Windowing.Desktop;

namespace test_CreateWindow
{
class Program
{
static void Main(string[] args)
{
var nativeWindowSettings = new NativeWindowSettings()
{
Size = new Vector2i(800, 600), // 窗口界面的尺寸为(800, 600)
Title = "test_CreateWindow", // 其他可用的参数可以点击NativeWindowSettings进行查看
};

using (Game game = new Game(GameWindowSettings.Default, nativeWindowSettings))
{
game.Run(); // 类似于Python,PyGame包中的mainloop,主循环开启,使得GUI窗口可以得以保持
}
}
}
}

​using OpenTK.Mathematics;​​​:代码中使用到的​​Vector2i​​​对象所在域名,因此我们需要进行引用。
​​​using OpenTK.Windowing.Desktop;​​​:代码中使用到的​​NativeWindowSettings​​对象所在域名,因此我们需要进行引用。

  1. 构建主程序中调用的​​GUI​​窗口界面的类
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;

namespace test_CreateWindow
{
// 从GameWindow对象中继承
public class Game : GameWindow
{
// 构造函数
public Game(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings) : base(gameWindowSettings, nativeWindowSettings)
{

}

// 所有的override方法都应该写入Game.cs类文件中而不应该在主程序Program.cs中
protected override void OnUpdateFrame(FrameEventArgs e)
{
// var input = KeyboardState;
// 上述代码应该等同于下面的代码
KeyboardState input = KeyboardState;

// 注意这里是Keys而不再是Key, 老版本中使用的是Key。
if (input.IsKeyDown(Keys.Escape))
{
// 使用close而不是exit, close是GameWindow中定义的方法
Close();
}

base.OnUpdateFrame(e);
}

}
}

​using OpenTK.Windowing.Desktop;​​​:代码中使用到的​​GameWindow​​​对象所在域名,因此我们需要进行引用。
​​​using OpenTK.Windowing.GraphicsLibraryFramework;​​​:代码中使用到的​​KeyboardState​​​对象所在域名,因此我们需要进行引用。
​​​using OpenTK.Windowing.Common;​​​:代码中使用到的​​FrameEventArges​​​对象所在域名,因此我们需要进行引用。此外,我们自己创建的域名,里面包含了我们自己创建的渲染器​​Shader​​​类,​​Camera​​​类以及​​Texture​​类。之后我们进行实际项目时会进一步提及。

KeyboardState input = KeyboardState;

if (input.IsKeyDown(Keys.Escape))
{
Close();
}

上述代码实现了运行代码打开​​GUI​​​界面后键盘按下​​Esc​​键后退出程序。

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~