我正在尝试以编程方式为OS应用程序创建一个带有OpenGL上下文的Cocoa窗口。我在网上找不到一个不使用界面生成器来创建窗口和OpenGL视图的示例。
我只想让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;
@endAppDelegate.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;
}
@endmain.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);
}发布于 2013-01-21 04:41:23
-[NSOpenGLContext flushBuffer]的文档中写道:
讨论
如果接收方不是双缓冲上下文,则此调用不执行任何操作。
您可以通过在像素格式属性中包含NSOpenGLPFADoubleBuffer来使您的上下文双缓冲。或者,您可以调用glFlush()而不是-[NSOpenGLContext flushBuffer],并让您的上下文保持单缓冲。
发布于 2015-04-27 13:41:00
将此代码用于像素格式属性。
NSOpenGLPixelFormatAttribute glAttributes[] =
{
NSOpenGLPFAColorSize, 24,
NSOpenGLPFAAlphaSize, 8,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAAccelerated,
0
};我已经测试过了,你得到了你想要的洋红色屏幕。
https://stackoverflow.com/questions/14427487
复制相似问题