macos - Cocoa 的 OpenGL 上下文 (OS X)

标签 macos cocoa opengl

我正在尝试以编程方式为 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/

相关文章:

macos - Mac 守护进程 howto(由 'book' 提供)

c++ - CreateDC 和 wglMakeCurrent 的问题

c++ - 好的 Linux/Ubuntu OpenGL 教程?

java - 为什么这个 SpriteBatch 在 C# 中工作而不在 Java 中工作?

macos - OSX/macOS - 如何将 xib 迁移到 Storyboard

ios - Toast 的 showMessage 函数未出现在 XLPagerTabStrip 中

macos - brew 更新失败并出现 "Permission denied"错误

objective-c - NSStatusitem 中的 NSTextField

swift - 窗口在所有空间可见(包括其他全屏应用程序)

objective-c - 在 obj-c 中设置文件的组和所有者