我正在尝试以编程方式为 OS X 应用程序创建一个带有 OpenGL 上下文的 Cocoa 窗口。我无法在网上找到不使用 Interface Builder 创建窗口和 OpenGL View 的示例。
我想要的只是让 glClear
将我的窗口变成洋红色 (0xFF00FF)。但是,窗口仍然是白色的。
这是我的项目:
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
NSOpenGLContext *openGLContext;
}
@property (assign) NSWindow *window;
@property (assign) NSOpenGLContext *openGLContext;
- (void)draw;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window;
@synthesize openGLContext;
static NSOpenGLPixelFormatAttribute glAttributes[] = {
0
};
- (void)draw {
NSLog(@"Drawing...");
[self.openGLContext makeCurrentContext];
glClearColor(1, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
[self.openGLContext flushBuffer];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSRect frame = NSMakeRect(0, 0, 200, 200);
self.window = [[[NSWindow alloc]
initWithContentRect:frame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO] autorelease];
[self.window makeKeyAndOrderFront:nil];
NSOpenGLPixelFormat *pixelFormat
= [[NSOpenGLPixelFormat alloc] initWithAttributes:glAttributes];
self.openGLContext = [[NSOpenGLContext alloc]
initWithFormat:pixelFormat shareContext:nil];
[self.openGLContext setView:[self.window contentView]];
[NSTimer
scheduledTimerWithTimeInterval:.1
target:self
selector:@selector(draw)
userInfo:nil
repeats:YES];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)_app {
return YES;
}
@end
main.m
#import "AppDelegate.h"
#import <Cocoa/Cocoa.h>
int main(int argc, char **argv) {
AppDelegate *appDelegate = [[AppDelegate alloc] init];
return NSApplicationMain(argc, (const char **) argv);
}
最佳答案
-[NSOpenGLContextlushBuffer]
的文档说:
Discussion
If the receiver is not a double-buffered context, this call does nothing.
您可以通过在像素格式属性中包含 NSOpenGLPFADoubleBuffer
来使上下文成为双缓冲。或者,您可以调用 glFlush()
而不是 -[NSOpenGLContextlushBuffer]
并让您的上下文保持单缓冲。
关于macos - Cocoa 的 OpenGL 上下文 (OS X),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14427487/