objective-c - cocoa 和OpenGL : failed to draw cube

标签 objective-c cocoa opengl glut osx-mountain-lion

我正在制作一个简单的应用程序,我应该在其中绘制一个带有 GLUT 的立方体。
由于我已经使用纯 C 研究了 OpenGL,因此我很难理解应该调用哪些函数来初始化上下文,因为我不必再调用 glutInit 等函数。
所以我对 NSOpenGLView 进行了子类化,禁用了窗口的一次性内存并编写了以下代码:

@implementation MyView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        NSOpenGLContext* context=[self openGLContext];
        [context makeCurrentContext];
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(45, 1, 1, 1000);
        glShadeModel(GL_SMOOTH);
        glMatrixMode(GL_MODELVIEW);
        glEnable(GL_DEPTH_TEST);
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor4f(1, 0, 0, 0);
    glutSolidCube(10);

    glFlush();
}

但似乎我错过了一些东西,因为我看到了黑色 View ,但没有看到立方体。

最佳答案

您需要将initWithFrame中的代码移至prepareGL。例如

- (void)prepareOpenGL {
    NSOpenGLContext *context = [self openGLContext];
    [context makeCurrentContext];
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, 1, 1, 1000);
    glShadeModel(GL_SMOOTH);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
} 

关于objective-c - cocoa 和OpenGL : failed to draw cube,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675528/

相关文章:

iphone - 如何在一段时间后触发委托(delegate)方法?

iOS - 创建自定义推送转场动画

objective-c - NSAlert 中的 NSTextView 没有滚动条

cocoa - 如何在不使用已弃用的方法的情况下更改 NSTableView 的选择

opengl - 删除过多的代码

iphone - 在 iOS 中存储图像的最佳方式

ios - 如何正确更新AUSampler的loadInstrument属性?

objective-c - 如何以编程方式用 CoreData 行填充 NSArrayController?

performance - OpenGL/DirectX : How does Mipmapping improve performance?

c++ - GLSL 每像素点光着色