CPF 是開源的C#跨平臺UI框架,支持使用OpenGL來渲染,可以用來硬件加速播放視頻或者顯示3D模型
實現(xiàn)原理其實就是Skia用OpenGL后端,Skia里綁定GLView的OpenGL紋理,將紋理作為Skia的圖像混合繪制。
在CPF里使用OpenGL,不能選擇NetCore3.0和Net4,需要選擇Netcore3.1以及之后的版本。
Nuget里安裝最新版的CPF。另外安裝Silk.NET或者OpenTK來調用OpenGL繪制。
Program里需要開啟GPU,設置 UseGPU = true
class Program { [STAThread] static void Main(string[] args) { Application.Initialize( (OperatingSystemType.Windows, new WindowsPlatform(), new SkiaDrawingFactory { UseGPU = true }) , (OperatingSystemType.OSX, new CPF.Mac.MacPlatform(), new SkiaDrawingFactory { UseGPU = true })//如果需要支持Mac才需要 , (OperatingSystemType.Linux, new CPF.Linux.LinuxPlatform(), new SkiaDrawingFactory { UseGPU = true })//如果需要支持Linux才需要 ); Application.Run(new Window2_1_Colors()); } }
界面上添加 CPF.Skia.GLView 控件,GLLoaded為GL加載完成事件,GLRender為GL繪制事件。OpenGL就在這兩個事件里處理
Children.Add(new WindowFrame(this, new GLView { Width = "100%", Height = "100%", [nameof(GLView.GLLoaded)] = new CommandDescribe((s, e) => GLLoaded((GLView)s, (GLEventArgs)e)), [nameof(GLView.GLRender)] = new CommandDescribe((s, e) => GLRender((GLView)s, (GLEventArgs)e)), [nameof(GLView.MouseDown)] = new CommandDescribe((s, e) => MouseEvent((GLView)s, (MouseEventArgs)e)), [nameof(GLView.MouseUp)] = new CommandDescribe((s, e) => MouseEvent((GLView)s, (MouseEventArgs)e)), [nameof(GLView.MouseMove)] = new CommandDescribe((s, e) => MouseEvent((GLView)s, (MouseEventArgs)e)), }) { MaximizeBox = true });
Silk.Net初始化API
GL gl;//可以保存為全局的字段 void GLLoaded(GLView view, GLEventArgs args) { gl = GL.GetApi(args.Context.GetProcAddress); }
OpenTk初始化API
class Context : OpenTK.IBindingsContext {//定義API綁定的上下文 public IGlContext context; public IntPtr GetProcAddress(string procName) { return context.GetProcAddress(procName); } } void GLLoaded(GLView view, GLEventArgs args) {//初始化一次就行 GL.LoadBindings(new Context { context = args.Context }); }
在GLRender事件里繪制。默認情況下GLRender不會一直調用,因為繪制方式不是游戲那種實時刷新的。需要刷新的時候要主動調用Invalidate(),或者用定時器來實時調用Invalidate()。
void GLRender(GLView view, GLEventArgs args) { gl.Enable(GLEnum.DepthTest);//開啟深度測試 gl.DepthMask(true); //其他繪制代碼。。。。 //開啟深度測試之后要關閉,否則會無法顯示界面,同樣的,如果開啟了其他功能,繪制結束后記得關閉,否則可能影響界面繪制。因為和界面共享OpenGL的上下文。 gl.Disable(GLEnum.DepthTest); }
?
具體OpenGL的繪制教程你可以直接找Silk.NET或者OpenTK的教程就行。
運行效果
?
案例源碼下載:CPF_OpenGL文章來源:http://www.zghlxwxcb.cn/news/detail-748512.html
CPF開源地址:https://gitee.com/csharpui/CPF文章來源地址http://www.zghlxwxcb.cn/news/detail-748512.html
到了這里,關于在CPF里使用OpenGL做跨平臺桌面應用開發(fā)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!