2010-11-05 29 views
0

我有一個關於在Mac OS X中如何CAOpenGLLayer作品是否有可能提請的OpenGL比在CAOpenGLLayer-[CAOpenGLLayer drawInCGLContext:]方法以外的地方一般性的問題?呈現在OpenGL中使用CAOpenGLLayer

我正在使用Apple的示例代碼CALayerEssentials ,並將代碼從drawInCGLContext移至redrawGLContent。每次用戶單擊OpenGL窗口上的按鈕時,都會調用redrawGLContent方法。
當繪圖代碼在drawInCGLContext中時,它按預期繪製,但是當我將代碼移動到redrawGLContent下時,沒有任何東西繪製到OpenGL窗口。我試圖瞭解它是如何工作的。

-(IBAction)redrawGLContent:(id)sender 
{ 

// This part wass added, but does not draw the rectangle 

    float timeInterval=0; 
    GLfloat rotate = timeInterval * 60.0; // 60 degrees per second! 
    glClear(GL_COLOR_BUFFER_BIT); 
    glMatrixMode(GL_MODELVIEW); 
    glPushMatrix(); 
    glRotatef(rotate, 0.0, 0.0, 1.0); 
    glBegin(GL_QUADS); 
     glColor3f(1.0, 0.0, 0.0); 
     glVertex2f(-0.5, -0.5); 
     glVertex2f(-0.5, 0.5); 
     glVertex2f(0.5, 0.5); 
     glVertex2f(0.5, -0.5); 
    glEnd(); 
    glPopMatrix(); 
// up to here 

    // Just tell the layer to display itself and it will redraw 
    [hostCAOpenGLLayer.layer setNeedsDisplay]; 
} 

-(void)drawInCGLContext:(CGLContextObj)glContext pixelFormat:(CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp 
{ 

    // Set the current context to the one given to us. 
    CGLSetCurrentContext(glContext); 


/* This part was removed. When code is here the quad is displayed 

    GLfloat rotate = timeInterval * 60.0; // 60 degrees per second! 
    glClear(GL_COLOR_BUFFER_BIT); 
    glMatrixMode(GL_MODELVIEW); 
    glPushMatrix(); 
    glRotatef(rotate, 0.0, 0.0, 1.0); 
    glBegin(GL_QUADS); 
     glColor3f(1.0, 0.0, 0.0); 
     glVertex2f(-0.5, -0.5); 
     glVertex2f(-0.5, 0.5); 
     glVertex2f(0.5, 0.5); 
     glVertex2f(0.5, -0.5); 
    glEnd(); 
    glPopMatrix(); 
*/  
    // Call super to finalize the drawing. By default all it does is call glFlush(). 
    [super drawInCGLContext:glContext pixelFormat:pixelFormat forLayerTime:timeInterval displayTime:timeStamp]; 
} 
+0

我注意到你沒有在實現redrawGLContent時調用CGLSetCurrentContext。你確定當被調用的當前上下文與傳遞給drawInCGLContext的上下文相同嗎? – BinaryStar 2011-06-10 21:20:03

回答

1

我知道這個問題前一段時間被問過,但我想我會回答它爲了別人的利益。沒有什麼比在堆棧溢出問題上遇到的問題更確切地描述了你的問題,但是沒有答案;-)

我認爲BinaryStar已經在這裏碰到了頭。你的問題是你沒有一個有效的GL上下文來繪製。

當系統調用drawInCGLContext:pixelFormat:forLayerTime:displayTime:時,它會爲您提供一個可供您的代碼使用的上下文。例如,當前視口將在此上下文中設置,以便您正在繪製圖層bounds。在您調用自定義代碼時,您不能保證此上下文已正確設置,或者它甚至是當前上下文。

我認爲這裏的正確方法是將CAOpenGLLayer的異步屬性設置爲NO。然後從你的按鈕處理代碼中調用層setNeedsDisplay