gpt4 book ai didi

objective-c - 无法设置 NSOpenGLContext 的 View

转载 作者:行者123 更新时间:2023-12-03 16:35:13 25 4
gpt4 key购买 nike

(提前为这里看似大量的代码感到抱歉)我正在尝试使用 Cocoa 创建一个带有 OpenGL 上下文的窗口,但我发现我无法设置 的 view 属性我创建的 NSOpenGLContext

我不能简单地使用 NSOpenGLView,因为我需要与 C++ 绘图后端交互并使用多个上下文。我在这里发布的代码只是我试图掌握处理 NSOpenGLContext 的方法,但它将用于更大的项目。这就是为什么我手动实例化 NSApplication 和我的 NSWindow,而不是通过 NIB/NSApplicationMain

我的ma​​in.m文件:

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import "Delegate.h"

int main(int argc, const char * argv[]) {

[NSApplication sharedApplication];
Delegate* dlg = [[Delegate alloc] init];

[NSApp setDelegate:dlg];

[NSApp run];

return 0;
}

然后,我有了我的委托(delegate)类,并且我将避免发布文件 Delegate.h,因为考虑到 Delegate.m 的这些内容,其中的内容将非常明显强>:

#import <Cocoa/Cocoa.h>
#import "Delegate.h"
#import <OpenGL/gl.h>

@implementation Delegate

- (void) draw
{
[self.glContext makeCurrentContext];

glClearColor(1, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);

[self.glContext flushBuffer];
}


- (void) applicationDidFinishLaunching:(NSNotification *)notification
{
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];

self.win = [[NSWindow alloc] initWithContentRect:NSMakeRect(30, 30, 300, 200)
styleMask:NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask
backing:NSBackingStoreBuffered
defer:YES];



NSOpenGLPixelFormatAttribute glAttributes[] =
{
NSOpenGLPFAColorSize, 24,
NSOpenGLPFAAlphaSize, 8,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAAccelerated,
0
};

self.glContext = [[NSOpenGLContext alloc] initWithFormat:[[NSOpenGLPixelFormat alloc] initWithAttributes:glAttributes]
shareContext:nil];
[self.glContext setView: [self.win contentView]];
printf("view:%p, contentView:%p\n", [self.glContext view], [self.win contentView]);


[self.win makeKeyAndOrderFront:nil];

[NSTimer
scheduledTimerWithTimeInterval:.1
target:self
selector:@selector(draw)
userInfo:nil
repeats:YES];
}

窗口打开得很好。我可以看出 -applicationDidFinishLaunching-draw 正在被调用。然而该窗口显示为空。

printf 调用显示 self.glContext 的 View 属性等于地址 0x0。我没有看到任何文档或其他论坛帖子说明为什么我无法设置 NSOpenGLContext 的可绘制对象。

我尝试将 NSOpenGLContext 放入其自己的 NSView 子类中,并将该子类添加为窗口内容 View 的 subview ,但没有成功。

最佳答案

尝试将 -[NSWindow initWithContentRect:...]defer 参数设置为 NO。您可能还希望在屏幕上订购窗口后设置 GL 上下文的 View 。

基本上,如果 View 的窗口还没有“设备”,-[NSOpenGLContext setView:] 可能会失败。当这种情况发生在我身上时,它通常会向控制台记录一条有关“无效可绘制对象”的消息,但我没有在最新版本的操作系统中进行检查。

此外,您还需要从 View 注册为 NSViewGlobalFrameDidChangeNotification 通知的观察者,并作为响应,在 GL 上下文对象上调用 -update

关于objective-c - 无法设置 NSOpenGLContext 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com