首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Cocoa的OpenGL上下文(OS X)

使用Cocoa的OpenGL上下文(OS X)
EN

Stack Overflow用户
提问于 2013-01-21 02:01:37
回答 2查看 4K关注 0票数 1

我正在尝试以编程方式为OS应用程序创建一个带有OpenGL上下文的Cocoa窗口。我在网上找不到一个不使用界面生成器来创建窗口和OpenGL视图的示例。

我只想让glClear让我的窗口变成洋红色(0xFF00FF)。但是,该窗口保持为白色。

这是我的项目:

AppDelegate.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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

代码语言:javascript
复制
#import "AppDelegate.h"

#import <Cocoa/Cocoa.h>

int main(int argc, char **argv) {
    AppDelegate *appDelegate = [[AppDelegate alloc] init];
    return NSApplicationMain(argc, (const char **) argv);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-21 04:41:23

-[NSOpenGLContext flushBuffer]的文档中写道:

讨论

如果接收方不是双缓冲上下文,则此调用不执行任何操作。

您可以通过在像素格式属性中包含NSOpenGLPFADoubleBuffer来使您的上下文双缓冲。或者,您可以调用glFlush()而不是-[NSOpenGLContext flushBuffer],并让您的上下文保持单缓冲。

票数 2
EN

Stack Overflow用户

发布于 2015-04-27 13:41:00

将此代码用于像素格式属性。

代码语言:javascript
复制
NSOpenGLPixelFormatAttribute glAttributes[] =
{
    NSOpenGLPFAColorSize, 24,
    NSOpenGLPFAAlphaSize, 8,
    NSOpenGLPFADoubleBuffer,
    NSOpenGLPFAAccelerated,
    0
};

我已经测试过了,你得到了你想要的洋红色屏幕。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14427487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档